Java多线程笔记1--wait、notify

wait、notify学习小记。
一个不是太合适的场景:顾客等饭吃、厨子做饭、厨子做好饭并停止做饭、顾客吃饭、顾客吃完饭接着等饭吃、厨子接着做饭………

也不知道这段代码对不对
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
final Object lock = new Object();
Thread customerThread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
lock.wait();
} catch (Exception ex) {

}
}
while (true) {
synchronized (lock) {
try {
System.out.println("顾客吃完了,厨师可以继续做饭..............");
lock.notify();
lock.wait();
} catch (Exception ex) {

}
}
}
}
});
Thread cookThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (lock) {
System.out.println("厨师做好了,顾客可以吃了,暂停做饭");
lock.notify();
try {
lock.wait();
} catch (Exception ex) {

}
}
}
}
});
customerThread.start();
cookThread.start();


场景这样可能这样更合适:客人来了、客人点菜、客人等上菜、厨师做菜、厨师做好菜停止做菜、客人吃菜、客人吃完菜并走人、客人来了…………..
也不知道这段代码对不对
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
final Object lock = new Object();
Thread customerThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (lock) {
System.out.println("来客人了,客人点菜、等吃菜");
try {
lock.notify();
lock.wait();
Thread.sleep(1000);
System.out.println("客人吃完菜、走人");
} catch (Exception ex) {

}
}
}
}
});
Thread cookThread = new Thread(new Runnable() {
@Override
public void run() {
try {
lock.wait();
} catch (Exception ex) {

}
while (true) {
System.out.println("厨师开始做菜");
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (Exception ex) {

}
System.out.println("厨师做好了,客人可以吃了,暂停做菜");
lock.notify();
try {
lock.wait();
} catch (Exception ex) {

}
}
}
}
});
customerThread.start();
cookThread.start();

显示 Gitment 评论