-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultithreading
More file actions
97 lines (81 loc) · 2.32 KB
/
Copy pathMultithreading
File metadata and controls
97 lines (81 loc) · 2.32 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
INPUT:
class ChatUser extends Thread {
private volatile boolean running = true;
private volatile boolean suspended = false;
ChatUser(String name, int priority) {
super(name);
setPriority(priority);
}
public void run() {
while (running) {
// check suspend
synchronized (this) {
while (suspended) {
try {
wait();
} catch (InterruptedException e) {}
}
}
// simulate sending a message
System.out.println(getName() + " (priority " + getPriority() + ") is sending a message...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
System.out.println(getName() + " stopped.");
}
public void suspendUser() {
suspended = true;
}
public synchronized void resumeUser() {
suspended = false;
notify();
}
public void stopUser() {
running = false;
interrupt();
}
}
public class SimpleChat {
public static void main(String[] args) throws Exception {
ChatUser u1 = new ChatUser("Alice", Thread.NORM_PRIORITY);
ChatUser u2 = new ChatUser("Bob", Thread.MAX_PRIORITY);
u1.start();
u2.start();
System.out.println("Alice alive? " + u1.isAlive());
System.out.println("Bob alive? " + u2.isAlive());
Thread.sleep(2000);
System.out.println("Suspending Bob...");
u2.suspendUser();
Thread.sleep(2000);
System.out.println("Resuming Bob...");
u2.resumeUser();
Thread.sleep(2000);
System.out.println("Stopping Alice and Bob...");
u1.stopUser();
u2.stopUser();
u1.join();
u2.join();
System.out.println("Alice alive? " + u1.isAlive());
System.out.println("Bob alive? " + u2.isAlive());
System.out.println("Chat ended.");
}
}
OUTPUT:
Alice alive? true
Bob alive? true
Alice (priority 5) is sending a message...
Bob (priority 10) is sending a message...
...
Suspending Bob...
Alice (priority 5) is sending a message...
...
Resuming Bob...
Bob (priority 10) is sending a message...
...
Stopping Alice and Bob...
Alice stopped.
Bob stopped.
Alice alive? false
Bob alive? false
Chat ended.