Java多线程多个线程wait(),一个notify()唤醒,唤醒的顺序

 1 package thread;
 2 
 3 public class ThreadWN implements Runnable {
 4     public String name;
 5     public String getName() {
 6         return name;
 7     }
 8     static int a = 9;
 9     public ThreadWN(String name) {
10         this.name = name;
11     }
12     @Override
13     public void run() {
14         while (a > 0) {
15             synchronized (ThreadWN.class) {
16                 a--;
17                 System.out.println("当前执行"+this.name+",并进入等待中......." );
18                 try {
19                     ThreadWN.class.wait();
20                 } catch (InterruptedException e) {
21                     e.printStackTrace();
22                 }
23             }
24         }
25     }
26 
27     public static void main(String[] args) throws InterruptedException {
28         TestTH tth =new TestTH("唤醒");
29         Thread t =new Thread(tth);
30         ThreadWN wna = new ThreadWN("A");
31         ThreadWN wnb = new ThreadWN("B");
32         ThreadWN wnc = new ThreadWN("C");
33         ThreadWN wnd = new ThreadWN("D");
34         ThreadWN wne = new ThreadWN("E");
35         ThreadWN wnf = new ThreadWN("F");
36         Thread tha = new Thread(wna);
37         Thread thb = new Thread(wnb);
38         Thread thc = new Thread(wnc);
39         Thread thd = new Thread(wnd);
40         Thread the = new Thread(wne);
41         Thread thf = new Thread(wnf);
42 
43         tha.start();
44         Thread.sleep(10);
45         thb.start();
46         Thread.sleep(10);
47         thc.start();
48         Thread.sleep(10);
49         thd.start();
50         Thread.sleep(10);
51         the.start();
52         Thread.sleep(10);
53         thf.start();
54         Thread.sleep(10);
55         t.start();
56         
57     }
58     
59 }
60 class TestTH implements Runnable{
61 
62     private String name;
63 
64     public TestTH(String name) {
65         this.name=name;
66     }
67     public String getName() {
68         return name;
69     }
70     @Override
71     public void run() {
72         for (int i = 0; i < 6; i++) {
73             synchronized (ThreadWN.class) {
74                 try {
75                     Thread.sleep(1000);
76                 } catch (InterruptedException e) {
77                     // TODO 自动生成的 catch 块
78                     e.printStackTrace();
79                 }
80                 System.out.println(this.getName()+"进程:"+"唤醒了一个线程!!!");
81                 ThreadWN.class.notify();
82                 }
83             }
84         }
85 
86     
87 }

猜你喜欢

转载自www.cnblogs.com/hyblogs/p/10418831.html