package cn.com.york.concurrency.demo;
public class ResearchThreadInterrupt implements Runnable {
/*
* 中断线程的方法: 1.设置共享变量,当变量为false时,退出线程。(这种情况适用于当前线程没有被阻塞,可以访问到共享变量)
* 2.利用Thread.interrupt(),跳出线程。(这种情况使用于该线程被阻塞,无法访问到共享变量)
* 下面的例子 讨论第二种情况。
*/
boolean stop = false;
int i=0;
Object obj = new Object();
/**
* 基本认识:第一个例子:thread.interrupt() 不会停止线程,在Thread.interrupt()被调用后,线程仍然继续运行。
*/
/*
public void run() {
while (!stop) {
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000)) {
}
}
System.out.println("Thread exiting under request...");
}
*/
// 第二个例子:用Thread.interrupt()设置中断状态为真,如果此时再调用sleep或者await方法阻塞线程,则抛出异常,中断线程
public void run() {
try {
synchronized(obj){
while (!stop) {
++i;
//Thread.currentThread().interrupt();
System.out.println("Thread running..."+" 中断状态:"+Thread.currentThread().isInterrupted());
//Thread.sleep(1000);
if(i>5)
obj.wait();
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000)) {
}
}
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted...");
}
System.out.println("Thread exiting under request...");
}
public static void main(String args[]) throws Exception {
ResearchThreadInterrupt rt = new ResearchThreadInterrupt();
Thread thread = new Thread(rt);
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.interrupt();
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit(0);
}
}