-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommunicationTest.java
More file actions
56 lines (43 loc) · 1.28 KB
/
CommunicationTest.java
File metadata and controls
56 lines (43 loc) · 1.28 KB
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
53
54
55
56
package Thread;
//线程的通信
//两个线程,交替打印1-100之间的数
class Number implements Runnable{
private int number = 1;
@Override
public void run() {
while(true){
synchronized(this){
if(number <= 100){
//唤醒被阻塞的线程
notify();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + number);
number ++;
//阻塞当前的线程,并释放锁
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
public class CommunicationTest {
public static void main(String[] args) {
Number num = new Number();
Thread t1 = new Thread(num);
Thread t2 = new Thread(num);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}