-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorker2.java
More file actions
63 lines (50 loc) · 1.59 KB
/
Worker2.java
File metadata and controls
63 lines (50 loc) · 1.59 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
package com.test.multithread;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
public class Worker2 extends Thread {
private SimpleDateFormat format;
private Object lock = new Object();
private volatile boolean quittingTime = false;
public void run() {
while (!quittingTime) {
working();
System.out.println(Thread.currentThread().getName() + " Still working...");
}
System.out.println(Thread.currentThread().getName() + " Coffe is good !");
}
private void working() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void quit() throws InterruptedException {
synchronized (lock) {
quittingTime = true;
System.out.println(Thread.currentThread().getName() + " Calling join");
join();
System.out.println(Thread.currentThread().getName() + " Back from join");
}
}
void keepWorking() {
synchronized (lock) {
quittingTime = false;
System.out.println(Thread.currentThread().getName() + " Keep working");
}
}
public static void main(String[] args) throws InterruptedException {
final Worker2 worker = new Worker2();
worker.start();
Timer t = new Timer(true);
t.schedule(new TimerTask() {
@Override
public void run() {
worker.keepWorking();
}
}, 500);
Thread.sleep(400);
worker.quit();
}
}