场景应用:银行转账时,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); } } }[注:A,B同在Thread-0下线程,C、D(另一A,B)同在Thread-1下线程。相互之间不影响。一个ThreadLocal代表一个变量,故其中只能放一个数据,你有两个变量都要线程范围内共享,则要定义两个ThreadLocal对象,如果有一百个变量要线程共享呢?那请先定义一个对象来封装这个变量,然后再ThreadLocal中存储这个对象。
ThreadLocal实现:java线程范围内的共享数据,线程外独立,布布扣,bubuko.com
ThreadLocal实现:java线程范围内的共享数据,线程外独立
原文:http://blog.csdn.net/u014078192/article/details/29367849