捕获中断信号关闭线程 package com . neu . day02 ; import java . util . concurrent . TimeUnit ; /** * @Author yqq * @Date 2022/03/27 18:50 * @Version 1.0 */ public class Thread05 { public static void main ( String [] args ) throws I
捕获中断信号关闭线程
package com.neu.day02;import java.util.concurrent.TimeUnit;
/**
* @Author yqq
* @Date 2022/03/27 18:50
* @Version 1.0
*/
public class Thread05 {
public static void main(String[] args) throws InterruptedException{
Thread t = new Thread(){
public void run() {
System.out.println("I will start work.");
while (!this.isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
};
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.interrupt();
}
}
使用 volatile 开关控制
package com.neu.day02;import java.util.concurrent.TimeUnit;
/**
* @Author yqq
* @Date 2022/03/27 19:02
* @Version 1.0
*/
public class Thread06 {
public static void main(String[] args) throws InterruptedException{
Mytask t = new Mytask();
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.close();
}
}
class Mytask extends Thread{
private volatile boolean closed = false;
public void run() {
System.out.println("I will start work.");
while (!closed && isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
public void close(){
this.closed = true;
this.interrupt();
}
}