【多线程】-线程范围内共享数据的两种方式

来源:互联网 发布:三星5830root软件 编辑:程序博客网 时间:2024/05/15 06:02

第一种,声明一个全局的map变量,用来存当前线程范围内的变量,用于线程范围内使用

//线程范围内共享变量public class ThreadScopeShareData {//声明一个存放全局变量的容器,来保存该变量在该线程范围内的状态private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();public static void main( String[] args){for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {int data = new Random().nextInt();System.out.println(Thread.currentThread().getName() + "has put data:" + data);threadData.put(Thread.currentThread(), data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);}}}

第二种,采用threadlocal方式(threadlocal这种变量,一个变量只能对应一个threadlocal,threadlocal原理其实就是一个map同上)

//线程范围内共享数据public class ThreadLocalTest {        //定义一个threadlocal变量,该threadlocal变量其实就相当于一个map        private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();        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() + "has put data:" + data);                                        //将数据存到当前线程里面                                        threadLocal.set(data);                                        new A().get();                                        new B().get();                                }                        }).start();                }        }                static class A{                public void get(){                        int data = threadLocal.get();                        System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);                }        }                static class B{                public void get(){                        int data = threadLocal.get();                        System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);                                        }        }}



原创粉丝点击