【JUC】08-中断机制之中断协商机制
1. 中断协商机制
一个线程应该自己主动去中断。所以Thread.stop, Thread.suspend, Thread.resume都已经被废弃。其他线程设置中断标识位为true,本线程会自行决定是否需要结束本线程。
void interrupt()
设置线程的中断状态为true,发起一个协商而不会立刻停止线程。static boolean interrupted()
判断线程是否被中断并清除当前中断状态:1. 返回当前线程的中断状态,测试当前线程是否已被中断; 2. 将当前线程的中断状态清零并重新设为false,清除线程的中断状态。boolean isInterrupted()
测试此线程是否已被中断。
public class SLEEPThread {public static void main(String[] args) {Thread t1 = new Thread(()->{while (true) {if (Thread.currentThread().isInterrupted()) {System.out.println("exit ..." + Thread.currentThread().isInterrupted());break;}try {/* 其他线程将中断标识位设置为true时,sleep方法会抛出InterruptedException,* 中断标识也被清空置为 false.*/Thread.sleep(200);} catch (InterruptedException e) {// 再次将 interrupted 设置为 falseThread.currentThread().interrupt();e.printStackTrace();}System.out.println("This is thread 1. Interrputed is " + Thread.currentThread().isInterrupted());}}, "t1");t1.start();try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}new Thread(()->{t1.interrupt();}, "t2").start();}
}
public class InterruptedDemo {public static void main(String[] args) {Thread.currentThread().interrupt();// trueSystem.out.println(Thread.currentThread().isInterrupted());// trueSystem.out.println(Thread.currentThread().isInterrupted());// true, 先返回真实值, 再将中断标识位设为falseSystem.out.println(Thread.interrupted());// falseSystem.out.println(Thread.interrupted());}
}
2. volatile实现线程中断
public class InterruptDemo {// volatile实现线程中断static volatile boolean isStop = false;public static void main(String[] args) {new Thread(()->{while (true) {if (isStop) {System.out.println("interrupt...");break;}System.out.println("Hello volatile.");}}, "t1").start();new Thread(()->{try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}isStop = true;},"t2").start();}
}
3. AtomicBoolean实现中断协商
public class AtomicBooleanDemo {static AtomicBoolean atomicBoolean = new AtomicBoolean(false);public static void main(String[] args) {new Thread(()->{while (true) {if (atomicBoolean.get()) {System.out.println("AtomicBoolean exit ...");break;}System.out.println("Hello Atomic ...");}}, "t1").start();new Thread(()->{try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}atomicBoolean.set(true);},"t2").start();}
}
4. Thread API实现协商中断
public class ThreadInterruptDemo {public static void main(String[] args) {Thread t1 = new Thread(() -> {/*当前线程处于阻塞状态(例如sleep、wait和join等状态),别的线程调用当前线程的interrupt方法,当前线程会退出阻塞,并抛出InterruptedException异常。*/try {TimeUnit.SECONDS.sleep(6);} catch (InterruptedException e) {throw new RuntimeException(e);}while (true) {if (Thread.currentThread().isInterrupted()) {System.out.println("eixt ...");break;}System.out.println("Hello");}}, "t1");t1.start();new Thread(()->{try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}t1.interrupt();},"t2").start();}
}