JAva volatileキーワードとinterrupt()を使用してスレッドを停止
2442 ワード
volatileキーの先行は後の変数の読み取り操作で発生する
interrupt()メソッドはスレッドを直接停止するのではなく、interruptのフラグビットを変更します.
public class Demo {
private volatile static boolean shutdown;
public static void main(String[] args) throws InterruptedException {
Runnable runnable=()->{
while (!shutdown){
System.out.println("safe...");
}
};
Thread t1 = new Thread(runnable, "t1");
t1.start();
System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
Thread.sleep(3000);
shutdown=true;
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
}
}
interrupt()メソッドはスレッドを直接停止するのではなく、interruptのフラグビットを変更します.
public class Demo {
private volatile static boolean shutdown;
public static void main(String[] args) throws InterruptedException {
Runnable interruptTask = new Runnable() {
@Override
public void run() {
int i = 0;
try {
// , ,
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(100); // 100ms
i++;
System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") loop " + i);
}
} catch (InterruptedException e) {
// InterruptedException 。( ,catch 。)
System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") catch InterruptedException.");
}
}
};
Thread t1 = new Thread(interruptTask, "t1");
System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
t1.start(); // “ t1”
System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
// 300ms, t1 “ ” 。
Thread.sleep(3000);
t1.interrupt();
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
// 300ms, t1 。
Thread.sleep(300);
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
}
}