欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ThreadLocal共享变量1

程序员文章站 2022-07-12 20:30:26
...
import java.util.Random;

public class ThreadLocalTest {
    private static ThreadLocal<Integer> x = new ThreadLocal();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int data = new Random().nextInt();
                    System.out.println(Thread.currentThread().getName() + ":" + data);
                    x.set(data);
                    new A().get();
                    new B().get();

                }
            }).start();
        }
    }

    static class A{
        public void get(){
            int data = x.get();
            System.out.println(Thread.currentThread().getName() + ":" + data);

        }
    }
    static class B{
        public void get(){
            int data = x.get();
            System.out.println(Thread.currentThread().getName() + ":" + data);
        }
    }
}

 

相关标签: thread java