java 多线程ThreadLocal
程序员文章站
2022-05-28 18:24:03
...
import java.util.Random; /*** * 线程内独享数据 ,多个线程内操作的数据互不干扰. * ThreadLocal 底层 采用的是 ThreadLocalMap * 自己实现的话就是 可以采用 Map<Thread.currentThread().getName(),value> * (个人理解 勿喷) */ public class ThreadLocalTest { /** * @param args */ private static ThreadLocal<Integer> x=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); x.set(data); MyThreadLocalData.getInstance().setName("name"+data); MyThreadLocalData.getInstance().setAge(data); new A().get(); new B().get(); } } ).start(); } } static class A{ public void get(){ int data =x.get(); System.out.println("A from "+Thread.currentThread().getName()+" get Date :"+data); } } static class B{ public void get(){ int data =x.get(); MyThreadLocalData mtld=MyThreadLocalData.getInstance(); System.out.println("B from "+Thread.currentThread().getName()+" get Date :"+mtld.getName()+" --age--"+mtld.getAge()); System.out.println("B from "+Thread.currentThread().getName()+" get Date :"+data); } } } class MyThreadLocalData{ private int age; private String name; private MyThreadLocalData(){} private static ThreadLocal<MyThreadLocalData> map=new ThreadLocal<MyThreadLocalData>(); public static MyThreadLocalData getInstance(){ MyThreadLocalData data=map.get(); if(data==null){ data=new MyThreadLocalData(); map.set(data); } return data; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
上一篇: java 定时器 Timer
下一篇: 赶集网MySQL开发33条军规