首页 > 学院 > 开发设计 > 正文

ThreadLocal类应用

2019-11-08 01:55:11
字体:
来源:转载
供稿:网友

      每个线程提供不同的变量拷贝 PRivate static ThreadLocal<Integer> x = new ThreadLocal<Integer>();

     例子:

//每个线程提供不同的变量拷贝public class TraditionalThreadLoal {      static Integer  itCommon = new Integer(0);//每个线程会拥有独自it变量public static void main(String[] args) {final ThreadLocal<Integer>  it = new ThreadLocal<>();//每个线程会拥有独自it变量     new Thread(new Runnable() {@Overridepublic void run() {for(int i=0;i<10;i++){it.set(i);itCommon = i;System.out.println("1->"+it.get());System.out.println("itCommon->"+itCommon);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}  }).start();       new Thread(new Runnable() {@Overridepublic void run() {for(int i=0;i<10;i++){it.set(i);itCommon = i;System.out.println("2->"+it.get());System.out.println("itCommon->"+itCommon);try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表