-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSuspendResume.java
More file actions
79 lines (69 loc) · 2.19 KB
/
SuspendResume.java
File metadata and controls
79 lines (69 loc) · 2.19 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
package chapter11;
//Suspending and resuming a thread the modern way
class NewThread5 implements Runnable {
String name; //name of thread
Thread t;
boolean suspendFlag;
public NewThread5(String threadName) {
this.name = threadName;
t = new Thread(this, name);
System.out.println("New Thread " + t);
suspendFlag = false;
}
//This is the entry point for the 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) {
NewThread5 ob1 = new NewThread5("One");
NewThread5 ob2 = new NewThread5("Two");
ob1.t.start(); //Start the thread
ob2.t.start(); //Start the thread
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");
}
}