-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutiThreadTest.java
More file actions
100 lines (83 loc) · 3.09 KB
/
Copy pathMutiThreadTest.java
File metadata and controls
100 lines (83 loc) · 3.09 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package MultiThreadTest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author tktktkl@foxmail.com
* @date 2019/7/10 20:36
*/
public class MutiThreadTest {
private static Object resource1 = new Object ();
private static Object resource2 = new Object ();
private static boolean flag = true;
public static void main (String[] args) throws InterruptedException {
Thread t1 = new Thread (new wait (), "t1");
t1.start ();
TimeUnit.SECONDS.sleep (2);
Thread t2 = new Thread (new notify (), "t2");
t2.start ();
// new Thread(()->{
// synchronized (resource1){
// System.out.println(Thread.currentThread()+"get r1");
// try{
// Thread.sleep(1000);
// }catch (InterruptedException e){
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread()+"waiting get r2");
// synchronized (resource2){
// System.out.println(Thread.currentThread()+"get r2");
// }
// }
//
// },"xc1").start();
//
// new Thread(()->{
// synchronized(resource1){
// System.out.println(Thread.currentThread()+"get r2");
// try{
// Thread.sleep(1000);
// }catch (InterruptedException e){
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread()+"waiting get r1");
// synchronized (resource2){
// System.out.println(Thread.currentThread()+"get r1");
// }
// }
//
// },"xc2").start();
// ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();
// ThreadInfo[]threadInfos=threadMXBean.dumpAllThreads(false, false);
// for (ThreadInfo threadInfo:threadInfos){
// System.out.println("["+threadInfo.getThreadId()+"]"+threadInfo.getThreadName());
// }
}
public static class wait implements Runnable {
@Override
public void run () {
synchronized (resource1) {
while (flag) {
System.out.println (Thread.currentThread () + " flag true" + new SimpleDateFormat ("HH:mm:ss").format (new Date ()));
try {
resource1.wait ();
} catch (InterruptedException e) {
e.printStackTrace ();
}
}
System.out.println (Thread.currentThread () + "flag is false");
}
}
}
public static class notify implements Runnable {
@Override
public void run () {
synchronized (resource1) {
System.out.println (Thread.currentThread () + " flag false" + new SimpleDateFormat ("HH:mm:ss").format (new Date ()));
resource1.notifyAll ();
flag = false;
}
System.out.println ("flag is false");
}
}
}