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