-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCancel.java
More file actions
50 lines (44 loc) · 1.14 KB
/
Copy pathTestCancel.java
File metadata and controls
50 lines (44 loc) · 1.14 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
/**
* Demonstration of interrupting a Java thread.
*/
class Worker implements Runnable
{
/**
* Method invoked by workers ...
*/
public void doWork() throws InterruptedException {
try {
Thread.sleep(1000);
}
catch (InterruptedException ie) {
throw ie;
}
}
/**
* The thread may be interrupted either when in the
* doWork() method, or it checks its interruption
* status with the isInterrupted() method.
*/
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
doWork();
System.out.println("I am a thread\n");
}
}
catch (InterruptedException ie) {
// caught exception thrown from doWork()
}
}
}
public class TestCancel
{
public static void main(String[] args) throws InterruptedException {
Runnable task = new Worker();
Thread worker = new Thread(task);
worker.start();
Thread.sleep(3000);
// sets the interruption status of the worker thread
worker.interrupt();
}
}