Java多线程wait和notify协作,按序打印abc

有一个经典的多线程面试题:启三个线程,按序打印ABC

上代码:

 1 package cn.javaBase.study_thread1;
 2 
 3 
 4 class MyRunnable1 implements Runnable {
 5     private Object prev;
 6     private Object self;
 7     private String name;
 8     
 9     public MyRunnable1(String n, Object p, Object s) {
10         this.name = n;
11         this.prev = p;
12         this.self = s;
13     }
14     
15     @Override
16     public void run() {
17         while (true) {
18             synchronized (prev) {
19                 synchronized (self) {
20                     System.out.println(name);
21                     self.notify();
22                 }
23                 try {
24                     prev.wait();
25                 } catch (InterruptedException e) {
26                     e.printStackTrace();
27                 }
28             }
29         }
30     }
31 }
32 
33 public class Thread5ABC {
34 
35     public static void main(String[] args) throws InterruptedException {
36         Object a = new Object();
37         Object b = new Object();
38         Object c = new Object();
39         
40         MyRunnable1 ra = new MyRunnable1("a", c, a);
41         MyRunnable1 rb = new MyRunnable1("b", a, b);
42         MyRunnable1 rc = new MyRunnable1("c", b, c);
43 
44         new Thread(ra).start();;
45         Thread.sleep(200);
46         new Thread(rb).start();
47         Thread.sleep(200);
48         new Thread(rc).start();
49         Thread.sleep(200);
50         
51     }
52 }

打印的结果,就是循环的打印abcabcabcabc

Java多线程wait和notify协作,按序打印abc_第1张图片

转载于:https://www.cnblogs.com/WNof11020520/p/8794191.html

你可能感兴趣的:(Java多线程wait和notify协作,按序打印abc)