Wait

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
49
50
51
52
package 锁wait;

/**
* @Author: 赵博雅
* @Date: 2020/6/10 0:16
*/
public class wait {

public static void main(String[] args) {

waitTest waitTist = new waitTest("线程1");

synchronized (waitTist){
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " 启动...");

waitTist.start();

try {
waitTist.wait(); //主线程进入等待状态
System.out.println(threadName + " 接着运行...");

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class waitTest extends Thread {

public waitTest(String name) {
super(name);
}

public void run() {
synchronized (this){
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " 启动...");
try {
System.out.println(threadName + " 工作中...");
Thread.sleep(5000);

System.out.println(threadName + " 完成...");
this.notify(); //使其他线程进入就绪状态
} catch (Exception e) {
e.printStackTrace();
}
}

}
}

“wait”的运行结果