说起线程共享数据有几种方式,
1.使用公共集合类来实现,代码很简单就不多解释:
public class TestThreadShareData { private static int data = 0; private static Map<Thread,Integer> map = new HashMap<Thread,Integer>(); public static void main(String[] args) { for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { data = new Random().nextInt(); map.put(Thread.currentThread(), data); System.out.println("main" + Thread.currentThread().getName() + "data=" + data); new A().get(); new B().get(); } }).start(); } } static class A { public void get() { data = map.get(Thread.currentThread()); System.out.println("A from main"+Thread.currentThread().getName() + "data = "+data); } } static class B { public void get() { data = map.get(Thread.currentThread()); System.out.println("B from main"+Thread.currentThread().getName() + "data = "+data); } } }
2.使用互斥的访问机制
public class doThreadShareData { //java.util.concurrent public static void main(String[] args) { ShareData shareData =new ShareData(); new Thread(new Runnable() { @Override public void run() { shareData.deccreament(); } }).start(); new Thread(new Runnable() { @Override public void run() { shareData.increment(); } }).start(); } } class ShareData { private int j = 0; public synchronized void increment(){ j++; } public synchronized void deccreament(){ j--; } }