• Java 多线程--ThreadLocal Timer ExecutorService


    ThreadLocal

    /**
     * ThreadLocal:每个线程自身的存储本地、局部区域
     * @author xzlf
     *
     */
    public class ThreadLocalTest01 {
    //	private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
    	// 更改初始化值
    	/*private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
    		protected Integer initialValue() {
    			return 100;};
    	};*/
    	
    	private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>().withInitial(()->50);
    	public static void main(String[] args) {
    		// 获取
    		System.out.println(Thread.currentThread().getName() +"-->" + threadLocal.get());
    		// 设置
    		threadLocal.set(200);
    		System.out.println(Thread.currentThread().getName() +"-->" + threadLocal.get());
    	}
    }
    
    **
     * ThreadLocal:每个线程自身的数据,更改不会影响其他线程
     * @author xzlf
     *
     */
    public class TheadLocalTest02 {
    	private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>().withInitial(()->1);
    	public static void main(String[] args) {
    		for(int i=0; i<5; i++) {
    			new Thread(new MyRun()).start();
    		}
    	}
    	
    	public static class MyRun implements Runnable{
    		@Override
    		public void run() {
    			int left = threadLocal.get();
    			System.out.println(Thread.currentThread().getName() + "得到了-->" + left);
    			threadLocal.set(left - 1);
    			System.out.println(Thread.currentThread().getName() + "还剩下-->" + threadLocal.get());
    			
    		}
    	}
    }
    
    
    /**
     * ThreadLocal:分析上下文 环境  起点
     * 1、构造器: 哪里调用 就属于哪里 找线程体
     * 2、run方法:本线程自身的
     * @author xzlf
     *
     */
    public class TheadLocalTest03 {
    	private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
    		protected Integer initialValue() {
    			return 100;
    		};
    	};
    	
    	public static void main(String[] args) {
    		new Thread(new MyRun()).start();
    		new Thread(new MyRun()).start();
    	}
    	
    	static class MyRun implements Runnable{
    		public MyRun() {
    			threadLocal.set(200);
    			System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
    		}
    		@Override
    		public void run() {
    			System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
    			
    		}
    	}
    	
    }
    
    

    运行:

    
    /**
     * InheritableThreadLocal:继承环境上下文的数据,拷贝一份给子线程
     * 
     * @author xzlf
     *
     */
    public class TheadLocalTest04 {
    	private static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<Integer>();
    	public static void main(String[] args) {
    		threadLocal.set(2);
    		System.out.println(Thread.currentThread().getName()+"-->"+threadLocal.get());
    		new Thread(()-> {
    			System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
    			threadLocal.set(100);
    			System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
    		}).start();
    	}
    	
    }
    

    运行:

    ExcutorService

    线程池

    public class TestFutrueTask {
    	public static void main(String[] args) throws InterruptedException, ExecutionException {
    		// 创建任务
    		MyCall call = new MyCall();
    		// 交给任务管理器
    		FutureTask<String> task = new FutureTask<String>(call);
    		// 创建代理类并启动线程
    		new Thread(task).start();
    		System.out.println("获取结果-->" + task.get());
    		System.out.println("任务是否执行完成-->" + task.isDone());
    	}
    }
    

    线程池执行带返回值的callable时需要加入到集合中,避免get() 等待结果是阻塞

    package com.xzlf.testThread;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.FutureTask;
    
    public class TestPool2 {
    	public static void main(String[] args) throws Exception, Exception {
    		// 创建一个线程池,线程池中只有一个线程对象
    //		ExecutorService pool = Executors.newSingleThreadExecutor();
    		// 创建一个线程池,线程池中数量固定
    		ExecutorService pool = Executors.newFixedThreadPool(10);
    		// 创建一个线程池,线程池中数量可以动态改变
    //		ExecutorService pool = Executors.newCachedThreadPool();
    		
    		List<Future<Integer>> list = new ArrayList<Future<Integer>>();
    		/**使用线程池执行大量的Callable任务*/
    		for (int i = 0; i < 20; i++) {
    			Callable<Integer> command = new Callable<Integer>() {
    
    				@Override
    				public Integer call() throws Exception {
    					Thread.sleep(2000);
    					return (int) (Math.random()*10);
    				}
    				
    			};
    			// 将任务交给线程池
    			FutureTask<Integer> task =(FutureTask<Integer>) pool.submit(command);
    			list.add(task);
    //			pool.execute(task);
    //			System.out.println(task.get());
    			
    		}
    		System.out.println("ok?");
    		for (Future<Integer> f : list) {
    			System.out.println(f.get());
    		}
    		System.out.println("ok!");
    		pool.shutdown();
    	}
    }
    
    

    运行:

    Timer

    package com.xzlf.testThread;
    
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class TestTimer {
    	public static void main(String[] args) throws InterruptedException {
    		// 创建Timer对象
    		Timer timer = new Timer();
    		// 创建任务对象
    		TimerTask task = new Clock();
    		// 调用schedule()方法执行任务
    		timer.schedule(task, new Date(System.currentTimeMillis() + 2000), 1000);
    		Thread.sleep(5000);
    		timer.cancel();
    		
    	}
    }
    
    /**
     * 任务
     * @author xzlf
     *
     */
    class Clock extends TimerTask{
    	DateFormat df = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
    	@Override
    	public void run() {
    		Date date = new Date();
    		String dateStr = df.format(date);
    		System.out.println(dateStr);
    	}
    }
    
    

    运行:

    重视基础,才能走的更远。
  • 相关阅读:
    (win10 64位系统中)Visual Studio 2015+OpenCV 3.3.0环境搭建,100%成功
    flutter环境搭建
    并发
    java集合继承关系图
    java中反射的使用
    android使用http3
    java之结合代码理解synchronized关键字
    阿里云ECS服务器将默认的Ubuntu系统改成桌面版
    python之demo2----改编自python官方提供的turtle_yinyang.py画阴阳的demo
    python之demo1----改编自turtle.py文件中的demo
  • 原文地址:https://www.cnblogs.com/xzlf/p/12710173.html
Copyright © 2020-2023  润新知