package base;/*** interrupt() 通知目标线程中断,设置标志位来表示当前进程已经被中断* isInterupted() 判断进程是否被中断*intterrupted() 判断线程是否被中断,清除标志位*/public class InterruptThread {public static void main(String[] args) throws InterruptedException {sleepByInterruptThread();}/*** sleep()被中断抛出InterruptedException* @throws InterruptedException*/private static void sleepByInterruptThread() throws InterruptedException {Thread thread = new Thread() {@Overridepublic void run() {while (true) {//若当前线程被标记中断,则退出循环if(Thread.currentThread().isInterrupted()){System.out.println("Interrupted");break;}try {Thread.sleep(2000);} catch (InterruptedException e) {//Thread.sleep()由于中断而抛出异常,此时,它会清除中断标记,若不处理//那么下一次循环就无法捕获这个中断,所以下面才再设置中断标记System.out.println("interruptd when sleep");//设置中断状态,保证数据的完整性和一致性,让上面循环中断检查中断线程Thread.currentThread().interrupt();}Thread.yield();System.out.println("thread is not interrupted");}}};thread.start();Thread.sleep(2000);thread.interrupt();}/*** 虽然置上中断标志位,但没有中断处理逻辑,不能中断线程*/private static void UninterruptThread() throws InterruptedException {Thread thread = new Thread() {@Overridepublic void run() {while (true) {Thread.yield();System.out.println("thread is not interrupted");}}};thread.start();Thread.sleep(2000);thread.interrupt();}private static void interruptThread() throws InterruptedException {Thread thread = new Thread() {@Overridepublic void run() {while (true) {//若当前线程被标记中断,则退出循环if(Thread.currentThread().isInterrupted()){System.out.println("Interrupted");break;}Thread.yield();System.out.println("thread is not interrupted");}}};thread.start();Thread.sleep(2000);thread.interrupt();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。