模式之两阶段终止

打断 sleep,wait,join 的线程
这几个方法都会让线程进入阻塞状态
打断 sleep 的线程, 会清空打断状态,以 sleep 为例

    public static void test1() throws InterruptedException {
		Thread t1 = new Thread(() -> {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "t1");
		t1.start();
		Thread.sleep(500);
		t1.interrupt();
		System.out.println(" 打断状态: " + t1.isInterrupted());
	}

输出

 打断状态: false
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.weisoft.test.Test.lambda$0(Test.java:12)
	at java.lang.Thread.run(Unknown Source)

打断正常运行的线程

打断正常运行的线程, 不会清空打断状态

    public static void test2() throws InterruptedException {
		Thread t2 = new Thread(() -> {
			while (true) {
				Thread current = Thread.currentThread();
				boolean interrupted = current.isInterrupted();
				if (interrupted) {
					System.out.println(" 打断状态: " + interrupted);
					break;
				}
			}
		}, "t2");
		t2.start();
		Thread.sleep(500);
		t2.interrupt();
	}

输出

 打断状态: true

模式之两阶段终止:

public class Test3 {

	public static void main(String[] args) {
		TwoPhaseTermination tpt = new TwoPhaseTermination();
		tpt.start();
		try {
			Thread.sleep(3792);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		tpt.stop();
	}

}

class TwoPhaseTermination {

	private Thread monitor;

	public void start() {
		monitor = new Thread(() -> {
			while (true) {
				Thread current = Thread.currentThread();
				if (current.isInterrupted()) {
					System.out.println("料理后事");
					break;
				}
				try {
					Thread.sleep(1000);
					System.out.println("执行监控记录");
				} catch (InterruptedException e) {
					e.printStackTrace();
					current.interrupt();
				}
			}
		}) {
		};
		monitor.start();
	}

	public void stop() {
		monitor.interrupt();
	}

}

输出

执行监控记录
执行监控记录
执行监控记录
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
料理后事
	at com.weisoft.test.TwoPhaseTermination.lambda$0(Test3.java:31)
	at java.lang.Thread.run(Unknown Source)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值