同步

同步:

image

 join() 实现同步,

但常用的是另外一个方法(类似办业务的时候,电脑叫号, 后人员才去办业务):

 1 public class DemoClass4Thread4 {
 2    public static void main(String[] args) {
 3       //TODO 线程 同步
 4       //写个简单例子,来展现同步的流程
 5       Num num = new Num();
 6       Customer c = new Customer(num);
 7       c.start();
 8 
 9       Bank b = new Bank(num);
10       b.start();
11 
12       /*
13       * 输出结果:
14          我是1号,银行还没有开门,我在门口等一会
15          9.00开门了,开始叫好了
16          叫到我的号了,该我办业务了
17       * */
18    }
19 }
20 
21 class Num{
22 
23 }
24 
25 class Bank extends Thread {
26    private Num num;
27    public Bank(Num num) {
28       this.num = num;
29    }
30 
31    public void run() {
32       synchronized (num){
33           try {
34               Thread.sleep(3000);
35           } catch (InterruptedException e) {
36               throw new RuntimeException(e);
37           }
38           System.out.println("9.00开门了,开始叫好了");
39           num.notifyAll();
40       }
41    }
42 }
43 
44 class Customer extends Thread{
45    private Num num;
46    public Customer(Num num) {
47       this.num = num;
48    }
49 
50    public void run() {
51       synchronized (num) {
52          System.out.println("我是1号,银行还没有开门,我在门口等一会");
53           try {
54               num.wait();
55           } catch (InterruptedException e) {
56               throw new RuntimeException(e);
57           }
58          System.out.println("叫到我的号了,该我办业务了");
59       }
60    }
61 }

 

posted @ 2025-10-23 15:49  字节虫  阅读(11)  评论(0)    收藏  举报