1 package multithread4;
2
3
4
5
6 /*
7 * 等待/唤醒机制。
8 *
9 * 涉及的方法:
10 *
11 * 1,wait();让线程处于冻结状态,被wait的线程会被存储到线程池(等待集)中。
12 * 2,notify();唤醒线程池中的一个线程(任意)
13 * 3,notifyAll();唤醒线程池中的所有线程。
14 *
15 * 这些方法都必须定义在同步中。
16 * 因为这些方法是用于操作线程状态的方法。
17 * 必须要明确到底操作的是哪个锁上的线程。
18 *
19 * 为什么操作线程的方法wait notify notifyAll定义在了Object类中。
20 *
21 * 因为这些方法是监视器的方法。监视器其实就是锁。
22 * 锁可以是任意的对象,而任意的对象调用的方法一定定义在Object类中
23 *
24 *
25 */
26
27 //资源
28 class Resource{
29 private String name;
30 private String sex;
31 private boolean flag = false;
32
33 public synchronized void set(String name,String sex) {
34 if (flag) {
35 try {
36 this.wait();
37 } catch (InterruptedException e) {
38
39 }
40
41 }
42 this.name =name;
43 this.sex = sex;
44 flag = true;
45 this.notify();
46
47 }
48 public synchronized void out() {
49 if (!flag) {
50 try {
51 this.wait();
52 } catch (InterruptedException e) {
53
54 }
55 }
56 System.out.println(name+"...."+sex);
57 flag = false;
58 notify();
59 }
60 }
61
62 //输入
63 class Input implements Runnable{
64 Resource r;
65 // Object obj = new Object();
66 public Input(Resource r) {
67 this.r = r;
68 }
69 public void run() {
70 int x = 0;
71 while(true) {
72 if (x==0) {
73 r.set("mike", "nan");
74 }else {
75 r.set("丽丽", "女女女");
76 }
77 x = (x+1)%2;
78 }
79 }
80 }
81
82 //输出
83 class Output implements Runnable{
84 Resource r;
85 public Output(Resource r) {
86 this.r = r;
87 }
88 public void run() {
89 while(true) {
90 r.out();
91 }
92 }
93 }
94
95
96 public class ResourceDemo3 {
97
98 public static void main(String[] args) {
99 //创建资源
100 Resource r = new Resource();
101 //创建任务
102 Input in = new Input(r);
103 Output out = new Output(r);
104 //创建线程,执行路径
105 Thread t1 = new Thread(in);
106 Thread t2 = new Thread(out);
107 //开启线程
108 t1.start();
109 t2.start();
110 }
111
112 }