关闭线程
通过interruptionException
关闭
import java.util.concurrent.TimeUnit;
/**
* @author husky
* @date 2019/7/11 11:23
*/
public class CloseThreadByInterruptException {
public static void main(String[] args) {
Thread workThread = new Thread(){
@Override
public void run() {
System.out.println("i will start work");
for(;;){
//working
//使用时间模拟工作
long start = System.currentTimeMillis();
long end = start + 1000 * 5;
while(System.currentTimeMillis() <= end){
//do nothing
}
try{
TimeUnit.MICROSECONDS.sleep(1);
}catch (InterruptedException e){
break;
}
}
System.out.println("i will be exiting");
}
};
workThread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("work thread will be closed");
workThread.interrupt();
}
}
通过interrupt status
import java.util.concurrent.TimeUnit;
/**
* @author husky
* @date 2019/7/11 11:16
*/
public class CloseThreadByInterruptStatus {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run() {
while(!isInterrupted()){
//do something
}
}
};
t1.start();
// ensure thread is running
TimeUnit.SECONDS.sleep(1);
System.out.println("Thread will be closed");
t1.interrupt();
}
}
通过volatile
和interrupt status
关闭
import java.util.concurrent.TimeUnit;
/**
* @author husky
* @date 2019/7/11 11:39
*/
public class CloseThreadByVolatile {
static class WorkThread extends Thread{
private volatile boolean flag = false;
@Override
public void run() {
System.out.println("i will start work");
while(!flag&&!isInterrupted()){
//正在执行
}
System.out.println("i will be exiting");
}
public void close(){
this.flag = true;
this.interrupt();
}
}
public static void main(String[] args) {
WorkThread workThread = new WorkThread();
workThread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("System will be interrupt");
workThread.close();
}
}
总结
interrupt status容易被清除,所以推荐使用voliate和interrupt status混合使用