-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathBackgroundTimePrintTask.java
49 lines (43 loc) · 1.01 KB
/
BackgroundTimePrintTask.java
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
package br.com.leonardoz.patterns.task_cancel;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Pattern: Thread Task Cancel
*
* Example: Canceling a Background Timer Print Task.
*
*/
public class BackgroundTimePrintTask {
private Thread thread;
private Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
var date = new Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat().format(date));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// no need to interrupt() if you don't have anything throwing InterruptedException
thread.interrupt();
}
}
};
public void run() {
thread = new Thread(task);
thread.start();
}
public void cancel() {
if (thread != null) {
thread.interrupt();
}
}
public static void main(String[] args) {
var self = new BackgroundTimePrintTask();
self.run();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
self.cancel();
}
}