场景应用:银行转账时,A给B转账,C给D转账。两者都是调用的connection.begainTransaction();connection.commit();
如何才能保证A,B同在一个线程中,C、D同在一个线程中,且A,BC,D在线程内共享,在线程外独立。
方法一,Map<Thread, Integer>实现:
/**
* 线程范围内的共享数据
*/
package cn.itcast.lesson5;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class TestThreadLocal {
private static int data = 0;
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() {
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+" has put data"+data);
//将线程的数据以key,value的形式存储
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("B from " + Thread.currentThread().getName()
+" get data" + data);
}
}
}<span style="color:#ff0000;">
</span>
方法二,ThreadLocal实现:
package cn.itcast.lesson5;
import java.util.Random;
public class ThreadLocal11 {
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() {
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+" has put data"+data);
//将线程的数据以key,value的形式存储
x.set(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 data" + data);
}
}
static class B{
public void get(){
int data =x.get();
System.out.println("B from " + Thread.currentThread().getName()
+" get data" + data);
}
}
}