`

Thread.isInterrupted 的理解

阅读更多

interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。

 

当线程被阻塞的时候,比如被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞时。

调用它的interrput()方法。没有占用CPU运行的线程是不可能给自己的中断状态置位的。这就会产生一个InterruptedException异常,并且不会设置中断状态

 Interrupted的经典使用代码:

 

 //    Interrupted的经典使用代码
    public void run(){    
            try{    
                 ....    
                 while(!Thread.currentThread().isInterrupted()&& more work to do){    
                        // do more work;    
                 }    
            }catch(InterruptedException e){    
                        // thread was interrupted during sleep or wait    
            }    
            finally{    
                       // cleanup, if required    
            }    
    }  
 

 

但是对于sleep,wait,join 要如下处理:

private static void test5() throws Exception{
        Thread t = new Thread (){
            public void run(){  
                while(!Thread.currentThread().isInterrupted()){  
                	try {
						Thread.sleep(4000);
					} catch (InterruptedException e) {
						//这里因为线程已经在运行了,所以可以设置中断状态,
						//并且下次Thread.currentThread().isInterrupted() 会返回true
						Thread.currentThread().interrupt();
						e.printStackTrace();
					}
                    if(Thread.currentThread().isInterrupted()){  
                        System.out.println("Someone interrupted me.");  
                    }  
                    else{  
                        System.out.println("Thread is Going...");  
                    }
                }  
            }  
        }  ;  
        t.start();  
        Thread.sleep(3000);  
        //此时,线程在sleep,虽然被打断,仅仅是抛出异常从sleep中退出,不会设置中断状态
        t.interrupt(); 
	}

private static void test6() throws Exception{
        Thread t = new Thread (){
            public synchronized void  run(){  
                while(!Thread.currentThread().isInterrupted()){  
                	try {
                		System.out.println("wait");
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
						System.out.println();
						//false
						System.out.println(Thread.currentThread().isInterrupted());
						
						//这里因为线程已经在运行了,所以可以设置中断状态,
						//并且下次Thread.currentThread().isInterrupted() 会返回true
						Thread.currentThread().interrupt();
					}
                    if(Thread.currentThread().isInterrupted()){  
                        System.out.println("Someone interrupted me.");  
                    }  
                    else{  
                        System.out.println("Thread is Going...");  
                    }
                }  
            }  
        }  ;  
        t.start();  
        Thread.sleep(3000);  
        //此时,线程在sleep,虽然被打断,仅仅是抛出异常从sleep中退出,不会设置中断状态
        t.interrupt(); 
	}

 

 

下面的案例说明了这个问题:

 

 wait响应中断,会抛出异常,但是不会设置中断状态

/**
	 * wait响应中断,会抛出异常,但是不会设置中断状态
	 */
	private static void testWait() throws Exception {
		Thread t = new Thread(){
			public synchronized void  run() {
				try {
					System.out.println("internal thread running");
					this.wait();
					System.out.println("internal thread over");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				//false
				System.out.println(Thread.currentThread().isInterrupted()); 
			};
		};
		
		t.start();
		SleepUtils.sleep(1000);
		t.interrupt();
		System.out.println(t.isInterrupted());
		System.out.println("Main over");
	}

 

park的被中断后,不会抛出异常,另外会设置中断位

/**
	 * park响应中断,但是不会抛出异常
	 */
	private static void testPark() throws Exception {
		Thread t = new Thread(){
			public void run() {
				System.out.println("internal thread running");
				LockSupport.park(Thread.currentThread());
				System.out.println("internal thread over");
				//true
				System.out.println(Thread.currentThread().isInterrupted()); 
			};
		};
		
		t.start();
		SleepUtils.sleep(3000);
		t.interrupt();
		System.out.println("Main over");
	}

 

sleep 会抛出异常,但是不会设置中断状态

中断之后,再调用sleep 会抛出异常,并清理中断状态 (这里指 Thread.currentThread().interrupt())

/**
	 * sleep响应中断,会抛出异常,设置中断状态
	 * @throws Exception
	 */
	private static void testSleep() throws Exception {
		Thread t = new Thread(){
			public void run() {
				try {
					System.out.println("internal thread running");
					Thread.currentThread().sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				//false
				System.out.println("----"+Thread.currentThread().isInterrupted()); 
			};
		};
		
		t.start();
		SleepUtils.sleep(3000);
		t.interrupt();
		System.out.println("Main over");
	}

 

 运行中的线程,中断线程,不会终止线程的执行,只是改变了中断状态

 

/**
	 * 运行中的线程,打断,不会终止线程的执行,只是改变了中断状态
	 * 对于非阻塞中的线程, 只是改变了中断状态
	 */
	private static void test1() throws Exception{
        Thread t = new Thread (){
            public void run(){  
                while(true){  
                    if(Thread.currentThread().isInterrupted()){  
                        System.out.println("Someone interrupted me.");  
                    }  
                    else{  
                        System.out.println("Thread is Going...");  
                    }
                }  
            }  
        }  ;  
        t.start();  
        Thread.sleep(3000);  
        t.interrupt();  
  /**
     分析如上程序的结果: 
    在main线程sleep的过程中由于t线程中isInterrupted()为false所以不断的输出”Thread is going”。
    当调用t线程的interrupt()后t线程中isInterrupted()为true。此时会输出Someone interrupted me.
    而且线程并不会因为中断信号而停止运行。因为它只是被修改一个中断信号而已。

    当我们调用t.interrput()的时候,线程t的中断状态(interrupted status) 会被置位。
    我们可以通过Thread.currentThread().isInterrupted() 来检查这个布尔型的中断状态。
  */
	}
 

 

 如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么, 

它将接收到一个中断异常;如果线程被上述几种方法阻塞,正确的停止线程方式是设置共享变量,并调用interrupt()

 

private static void test2() throws Exception {
		Thread3 thread = new Thread3();
		System.out.println("Starting thread...");
		thread.start();

		Thread.sleep(3000);

		System.out.println("Asking thread to stop...");

		/*
		 * 如果线程阻塞,将不会检查此变量,调用interrupt之后,线程就可以尽早的终结被阻 塞状 态,能够检查这一变量。
		 */
		thread.stop = true;

		/*
		 * 这一方法实际上完成的是,在线程受到阻塞时抛出一个中断信号,这样线程就得以退 出阻 塞的状态
		 */
		thread.interrupt();

		Thread.sleep(3000);
		System.out.println("Stopping application...");
		System.exit(0);
	}

static class Thread3 extends Thread {
		volatile boolean stop = false;
		public void run() {
			while (!stop) {
				System.out.println("Thread running...");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// 接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态
					e.printStackTrace();
					System.out.println("Thread interrupted...");
				}
			}

			System.out.println("Thread exiting under request...");
		}
	}
 

 

 

0
1
分享到:
评论

相关推荐

    jlayer-1.0.1.jar

    Thread.currentThread().isInterrupted()) { System.out.println(!Thread.currentThread().isInterrupted()); //声明一个File对象 File mp3 = new File("E:\\Download\\10092.mp3"); ...

    Android开发笔记之:如何安全中止一个自定义线程Thread的方法

    经研究,我推荐这种写法: 代码如下:<SPAN xss=removed>/*自定义线程*/ class MyThread implements Runnable{ public void run() { // TODO Auto-generated ...Thread.currentThread().isInterrupted()){ try { do

    Thread类的interrupt(),interrupted(),isInterrupted()1

    一般来说,支持线程中断的方法(也就是线程中断后会抛出InterruptedException的方法),阻塞函数,如:Thread.sleep、Thread.jo

    java8源码-JavaSE-Code:JavaSE的代码练习与学习笔记总结

    interrupted是Thread类的静态方法,里面调用了isTnterrupted方法[currentThread().isInterrupted()],测试当前线程是否已经中断,线程的中断状态由该方法清除 isInterrupted是Thread类的实例方法,不清除中断标志 yield...

    Java中interrupt的使用.docx

    具体原因可以参考Why is Thread.stop deprecated。 在本文中,将讨论中断在java中的使用。 中断在java中主要有3个方法,interrupt(),isInterrupted()和interrupted()。 interrupt(),在一个线程中调用另一个线程...

    JAVA多线程之中断机制stop()、interrupted()、isInterrupted()

    主要介绍了JAVA多线程之中断机制stop()、interrupted()、isInterrupted()的相关资料,需要的朋友可以参考下

    android串口通信

    private class ReadThread extends Thread { @Override public void run() { super.run(); while(!isInterrupted()) { int size; try { byte[] buffer = new byte[64]; if (mInputStream == null...

    JUC学习.docx Java

    一. 1.创建线程: (1)在创建线程时,传入Runnable接口的实现类,重写run...(3)isInterrupted:判断当前是否有打断标记 (4)Interrupted:判断当前有打断标记,并且清除标记 (5)Park:LockSupport的静态方法,在调用时会

    java多线程Thread的实现方法代码详解

    主要介绍了java多线程Thread的实现方法代码详解,涉及start(),run(),stop(),interrupt(),isInterrupted(),join()和join(long millis)等方法的介绍,具有一定借鉴价值,需要的朋友可以了解下。

    线程中断的方法以及静态方法isInterrupted和实例方法interrupted的区别

    线程中断 常见的有以下两种方式: 通过共享的标记来进行沟通 调用 interrupt() 方法来通知 通过共享的标记来实现中断 就是创建一个boolean类型的变量来控制循环是否进行,就是一个标记。 代码如下: ...

    Java多线程教程吐血整理干货.md

    interrupt,interrupted,isInterrupted方法区别 join方法 yield方法 多线程 进程和线程 进程与线程最主要的区别是它们是操作系统管理资源的不同方式的体现。 准确来说进程与线程属于衍生关系。 进程是操作系统执行...

    Java期末复习||应用程序设计-多线程和泛型

    线程操作:isAlive()、isInterrupted()、join()、sleep()、stop()、interrupted()、setDaemon()、setPriority()、yield() 同步与死锁、Object类对线程的支持 泛型、通配符、受限泛型、泛型接口、泛型方法、泛型数字...

    anko2MikuMikuMouth:我会做的!Anko-chan插件

    isInterrupted 例子 { "name": "ゆかり", "text": "こんにちはみなさん", "emotion": "greeting", "tag": "white", "isInterrupted": false, } 如何使用 如果在Unity中使用它,则使用以下脚本会很方便。

    juc相关全套总结,全网最全,最精细。【请用MindManager打开,没有该破解软件的请留言】

    一个java的多线程juc总结,其中包含基础知识,现成的状态图,关于synchronized,线程优先级和线程分类,interrupt、interupted、isInterrupted的使用,sleep、yield、join的详细使用,锁和等待池介绍。

    Java中断一个线程操作示例

    主要介绍了Java中断一个线程操作,结合实例形式分析了java中断线程相关的interrupt()、isInterrupted()及interrupted()函数使用技巧,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics