java ThreadLocal例子

package test;

public class UseThreadLocal {
    
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
        protected Integer initialValue(){
            return 1;
        }
    };
    
    public void startThreadArray(){
        Thread[] runs = new Thread[3];
        for(int i = 0 ; i < runs.length;i++){
            runs[i]=new Thread(new TestThread(i));
        }
        for(int i = 0 ; i < runs.length;i++){
            runs[i].start();
        }
    }

    public static class TestThread implements Runnable{
        int id;
        public TestThread(int id){
            this.id=id; 
        }
        
        public void run(){
            System.out.println(Thread.currentThread().getName()+":start");
            Integer s = threadLocal.get();
            s=s+id;
            threadLocal.set(s);
            System.out.println(Thread.currentThread().getName()+":"+threadLocal.get());
        }
    }
    
    public static void main(String[] args) {
        UseThreadLocal test = new UseThreadLocal();
        test.startThreadArray();
    }
    
}
 

相关文章:

  • 2021-09-04
  • 2021-08-14
  • 2022-02-09
  • 2021-06-27
猜你喜欢
  • 2021-09-18
  • 2022-12-23
  • 2021-07-05
  • 2021-08-19
  • 2021-08-17
  • 2022-01-04
相关资源
相似解决方案