-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuspendResume.java
More file actions
74 lines (65 loc) · 2.1 KB
/
SuspendResume.java
File metadata and controls
74 lines (65 loc) · 2.1 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
// Suspending and resuming a thread the modern way.
class NewThreadSR implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThreadSR(String threadName) {
name = threadName;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
} }
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
synchronized void mySuspend() {
suspendFlag = true;
}
synchronized void myResume() {
suspendFlag = false;
notify();
} }
public class SuspendResume {
public static void main(String[] args) {
NewThreadSR ob1 = new NewThreadSR("One");
NewThreadSR ob2 = new NewThreadSR("Two");
try {
Thread.sleep(1000);
ob1.mySuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myResume();
System.out.println("Resuming thread One");
ob2.mySuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myResume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}