828. 如何在两个线程之间共享数据?

通过在线程之间共享对象就可以了,然后通过wait/notify/notifyAll、await/signal/signalAll进⾏唤起和等待,⽐⽅说阻塞队列BlockingQueue就是为线程之间共享数据⽽设计的。

  1. 卖票系统:
1 package 多线程共享数据;
2 public class Ticket implements Runnable{
3 private int ticket = 10;
4 public void run() {
5 while(ticket>0){
6 ticket--;
7 System.out.println("当前票数为:"+ticket);
8 }
9 }
10 }
11
12 package 多线程共享数据;
13 public class SellTicket {
14 public static void main(String[] args) {
15 Ticket t = new Ticket();
16 new Thread(t).start();
17 new Thread(t).start();
18 }
19 }
2. 银⾏存取款:
1 public class MyData {
2 private int j=0;
3 public synchronized void add(){
4 j++;
5 System.out.println("线程"+Thread.currentThread().getName()+"j为:"+j);
6 }
7 public synchronized void dec(){
8 j--;
9 System.out.println("线程"+Thread.currentThread().getName()+"j为:"+j);
10 }
11 public int getData(){
12 return j;
13 }
14 }
15
16 public class AddRunnable implements Runnable{
17 MyData data;
18 public AddRunnable(MyData data){
19 this.data= data;
20 }
21 public void run() {
22 data.add();
23 }
24 }
25
26 public class DecRunnable implements Runnable {
27 MyData data;
28 public DecRunnable(MyData data){
29 this.data = data;
30 }
31 public void run() {
32 data.dec();
33 }
34 }
35
36 public class TestOne {
37 public static void main(String[] args) {
38 MyData data = new MyData();
39 Runnable add = new AddRunnable(data);
40 Runnable dec = new DecRunnable(data);
41 for(int i=0;i<2;i++){
42 new Thread(add).start();
43 new Thread(dec).start();
44 }
45 }