blob: f50c41be4f59534bb9ae9d92fb98ac3f38de05e1 (
plain)
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 old.interruptThread.model;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 线程关闭模型1
* 宗旨:外部线程通知该线程中断,该线程自行业务结束
* 非阻塞的循环业务操作,在循环中使用stop标示来结束业务循环
*
* @date Feb 21, 2013 10:30:53 AM
* @author ZhangGang
*
*/
public class SimpleModel1 implements Runnable {
volatile boolean stop = false;
public static void main(String[] args) throws Exception {
// Thread thread = new Thread(new SimpleModel1(), "My Thread2");
ExecutorService service = Executors.newFixedThreadPool(1);
System.out.println("Starting thread...");
Future<String> future = service.submit(new SimpleModel1(),"");
Thread.sleep(4000);
System.out.println("Interrupting thread...");
future.cancel(true) ; // 中断线程
Thread.sleep(3000);
System.out.println("Stopping application...");
service.shutdownNow();
}
public void run() {
for (int i = 0; i < 10000000l && !stop; i++) {
/* 模拟睡眠1秒操作 替换为完整的业务 */
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000)) {
}
/**
* Thread.currentThread().isInterrupted() 为获取线程中断状态,获取后不改变状态值
* ps:catch(InterruptedException e)异常捕获 上面的取值会改变为false
*/
System.out.println("My Thread is running... isInterrupted? "+Thread.currentThread().isInterrupted());
if (Thread.currentThread().isInterrupted()) { // 该值为读取
// 线程中断状态,不会改变中断状态的值
System.out.println("结束线程...");
stop = true;
}
else if (Thread.currentThread().isInterrupted()) { // 该值为读取
System.out.println("结束线程...");
return;
}
/**
* if 和 else if的区别在于 else if没有"My Thread exiting under request..."的输出
* 推荐使用if 判断
* */
}
System.out.println("My Thread exiting under request...");
}
}
|