Java ThreadLocal多线程操作各自自己的对象 Demo

  • 代码
package threadlocal;

public class ThreadLocalDemo {
    public static void main(String[] args) {
        AccessCount accessCount = new AccessCount();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                Integer get = accessCount.counts.get();
                if (get == null){
                    accessCount.counts.set(1);
                }else {
                    accessCount.counts.set(get+1);
                }
            }
            System.out.println(Thread.currentThread().getName()+" count"+accessCount.counts.get());
        }).start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                Integer get = accessCount.counts.get();
                if (get == null){
                    accessCount.counts.set(1);
                }else {
                    accessCount.counts.set(get+1);
                }
            }
            System.out.println(Thread.currentThread().getName()+" count"+accessCount.counts.get());
        }).start();
    }
}
class AccessCount{
    public ThreadLocal<Integer> counts = new ThreadLocal<>();
}

  • 运行结果
    在这里插入图片描述
posted @ 2021-06-28 11:48  HumorChen99  阅读(1)  评论(0编辑  收藏  举报  来源