-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadDemo5.java
More file actions
76 lines (63 loc) · 1.75 KB
/
Copy pathThreadDemo5.java
File metadata and controls
76 lines (63 loc) · 1.75 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package thirdPart;
/**
* @author yangxp
* @date 2017年8月8日 下午4:12:42
* wait(long) 的使用方法,即时有时间性的等待
*/
public class ThreadDemo5 {
public static void main(String[] args) {
Object lock = new Object();
MyRunnable5A myRunnable5A = new MyRunnable5A(lock);
MyRunnable5B myRunnable5B = new MyRunnable5B(lock);
Thread a = new Thread(myRunnable5A.getRunnable());
a.start();
Thread b = new Thread(myRunnable5B.getRunnable());
b.start();
}
}
class MyRunnable5A {
private Object lock;
public MyRunnable5A(Object lock) {
this.lock = lock;
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("wait begin timer = " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
lock.wait(2000);
System.out.println("wait end timer = " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public Runnable getRunnable() {
return runnable;
}
}
class MyRunnable5B {
private Object lock;
public MyRunnable5B(Object lock) {
this.lock = lock;
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("notify begin timer = " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
lock.notify();
System.out.println("notify end timer = " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
public Runnable getRunnable() {
return runnable;
}
}