public class MultiThreadShareData { //多线程卖票,一个加,一个减
//private static ShareData1 data1 = new ShareData1(); public static void main(String[] args) { ShareData1 data2 = new ShareData1(); new Thread(new MyRunnable1(data2)).start(); new Thread(new MyRunnable2(data2)).start(); final ShareData1 data1 = new ShareData1(); new Thread(new Runnable(){ @Override public void run() { data1.decrement(); } }).start(); new Thread(new Runnable(){ @Override public void run() { data1.increment(); } }).start();
}
} class MyRunnable1 implements Runnable{ //线程1 private ShareData1 data1; public MyRunnable1(ShareData1 data1){ this.data1 = data1; } public void run() { data1.decrement(); } } class MyRunnable2 implements Runnable{ //线程2 private ShareData1 data1; public MyRunnable2(ShareData1 data1){ this.data1 = data1; } public void run() { data1.increment(); } }
class ShareData1 /*implements Runnable*/{ //共享对象 /* private int count = 100; @Override public void run() { // TODO Auto-generated method stub while(true){ count--; } }*/ private int j = 0; public synchronized void increment(){ j++; } public synchronized void decrement(){ j--; } }
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(){ @Override public void run() { int data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); 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); } } }
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); //存放与当前线程有关的数据 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); } } }