-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadTest5.java
More file actions
66 lines (58 loc) · 1.94 KB
/
ThreadTest5.java
File metadata and controls
66 lines (58 loc) · 1.94 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
package thread;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Administrator on 2017/5/10 0010.
*/
public class ThreadTest5 {
public static void main(String[] args) {
List list = new LinkedList();
Thread thread1 = new Thread(new ReadList(list));
Thread thread2 = new Thread(new WriteList(list));
thread1.start();
thread2.start();
}
}
class ReadList implements Runnable{
private List list;
public ReadList(List list) {
this.list = list;
}
@Override
public void run() {
System.out.println("ReadList begin at ---"+System.currentTimeMillis());
synchronized (list){
try {
Thread.sleep(1000);
System.out.println("ReadList list.wait() begin at ---"+System.currentTimeMillis());
list.wait();
System.out.println("ReadList list.wait() end at---"+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ReadList end at ---"+System.currentTimeMillis());
}
}
class WriteList implements Runnable{
private List list;
public WriteList(List list) {
this.list = list;
}
@Override
public void run() {
System.out.println("WriteList begin at ---"+System.currentTimeMillis());
synchronized (list){
System.out.println("WriteList get lock at ---"+System.currentTimeMillis());
list.notify();
System.out.println("WriteList list.notify(); at ---"+System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("WriteList get out of lock at ---"+System.currentTimeMillis());
}
System.out.println("WriteList end at ---"+System.currentTimeMillis());
}
}