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
public class NotifyTest {
public synchronized void testWait(){
System.out.println(Thread.currentThread().getName() +" Start-----");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" End-------");
}

public static void main(String[] args) throws InterruptedException {
final NotifyTest test = new NotifyTest();
// 创建五个线程取运行对象的方法
for(int i=0;i<5;i++) {
new Thread(new Runnable() {
@Override
public void run() {
test.testWait();
}
}).start();
}

//通知一个 线程
synchronized (test) {
test.notify();
}
Thread.sleep(3000);
System.out.println("-----------分割线-------------");
//通知所有线程
synchronized (test) {
test.notifyAll();
}
}
}
Donate comment here