多线程之中断线程详解编程语言

1、线程在运行过程中,有些时候可能需要中断一些阻塞的线程,类Thread中提供了几种中断线程的方法,其中Thread.suspend()和Thread.stop()方法已经过时了,因为这两个方法是不安全的。Thread.stop(),会直接终止该线程,并且会立即释放这个线程持有的所有锁,而这些锁恰恰是用来维持数据的一致性的,如果此时。写线程写入数据时写到一半,并强行终止,由于此时对象锁已经被释放,另一个等待该锁的读线程就会读到这个不一致的对象。Thread.suspend()会导致死锁,Thread.resume()也不能使用。
2、 中断机制中的方法有

  • interrupted() 类方法 用来判断当前线程的中断状态,并且会清除中断状态
  • interrupt() 实例方法 用来将调用此方法的线程的状态设置为中断
  • isInterrupted() 实例方法 用来判断调用次方法的线程的中断状态 ,不会清除中断状态

注意:interrupt 仅仅改变的是线程的状态,不会立即停掉某个线程。
如果是非阻塞线程,就仅仅是改变线程的状态。
如果是阻塞线程,就会抛出InterruptedException,并且会清除中断状态,详情看源码分析
比如 类方法 Object.wait(); 类方法 Thread.sleep(); 实例方法 .join()
3、 源码分析

interrupt()

/** 
     * Interrupts this thread. 要中断的线程 
	 *<注解一>若当前线程要中断它自己,这个是一直允许的。如果一个线程要终止另一个线程(不是它自己), 
	 * 要先checkAccess()检查权限,可能会抛出SecurityException 
     * <p> Unless the current thread is interrupting itself, which is 
     * always permitted, the [email protected] #checkAccess() checkAccess} method 
     * of this thread is invoked, which may cause a [email protected] 
     * SecurityException} to be thrown. 
     *<注解二>如果这个线程是调用了以下方法(wait,join,sleep)而进入阻塞,这时执行interrupt(),这个中断状态将会被清除并且抛出InterruptedException 
     * <p> If this thread is blocked in an invocation of the [email protected] 
     * Object#wait() wait()}, [email protected] Object#wait(long) wait(long)}, or [email protected] 
     * Object#wait(long, int) wait(long, int)} methods of the [email protected] Object} 
     * class, or of the [email protected] #join()}, [email protected] #join(long)}, [email protected] 
     * #join(long, int)}, [email protected] #sleep(long)}, or [email protected] #sleep(long, int)}, 
     * methods of this class, then its interrupt status will be cleared and it 
     * will receive an [email protected] InterruptedException}. 
     * 
     * <p> If this thread is blocked in an I/O operation upon an [email protected] 
     * java.nio.channels.InterruptibleChannel InterruptibleChannel} 
     * then the channel will be closed, the thread's interrupt 
     * status will be set, and the thread will receive a [email protected] 
     * java.nio.channels.ClosedByInterruptException}. 
     * 
     * <p> If this thread is blocked in a [email protected] java.nio.channels.Selector} 
     * then the thread's interrupt status will be set and it will return 
     * immediately from the selection operation, possibly with a non-zero 
     * value, just as if the selector's [email protected] 
     * java.nio.channels.Selector#wakeup wakeup} method were invoked. 
     *<注解三>如果线程没有因为以上的条件阻塞,那么中断状态将会被设置 
     * <p> If none of the previous conditions hold then this thread's interrupt 
     * status will be set. </p> 
     *<注解四>如果中断一个已经停止的线程,将不会有任何效果 
     * <p> Interrupting a thread that is not alive need not have any effect. 
     * 
     * @throws  SecurityException 
     *          if the current thread cannot modify this thread 
     * 
     * @revised 6.0 
     * @spec JSR-51 
     */ 
    public void interrupt() { 
	    //对应注解一 
        if (this != Thread.currentThread()) 
            checkAccess(); 
 
        synchronized (blockerLock) { 
            Interruptible b = blocker; 
            if (b != null) { 
                interrupt0();           // Just to set the interrupt flag 这是本地方法 
                b.interrupt(this); 
                return; 
            } 
        } 
        interrupt0(); 
    } 

isInterrupted()

 public boolean isInterrupted() { 
        return isInterrupted(false);//不会清除中断状态 
    } 

interrupted()

public static boolean interrupted() { 
        return currentThread().isInterrupted(true);//会清除中断状态 
    } 
 

这两个方法都是调用本地方法
private native boolean isInterrupted(boolean ClearInterrupted);//参数的意思是:是否清除中断状态

4、 代码实例

public class InterruptedDemo1 { 
	public static void main(String[] args) { 
		DemoThread demo = new DemoThread(); 
		demo.start(); 
		System.out.println("main-isInterrupted:"+demo.isInterrupted()); 
		try { 
			Thread.sleep(500); 
		} catch (InterruptedException e) { 
			e.printStackTrace(); 
		} 
		demo.interrupt(); 
		System.out.println("main-isInterrupted:"+demo.isInterrupted()); 
        System.out.println("Main thread stopped.");   
	} 
} 
class DemoThread extends Thread{ 
	@Override 
	public void run() { 
		while(true){ 
			try { 
				Thread.sleep(1000); 
			} catch (InterruptedException e) { 
				e.printStackTrace(); 
			} 
			System.out.println("sub-isInterrupted:"+Thread.currentThread().isInterrupted()); 
		} 
	} 
} 
//以下是打印的结果 
main-isInterrupted:false 
main-isInterrupted:true 
Main thread stopped. 
java.lang.InterruptedException: sleep interrupted 
	at java.lang.Thread.sleep(Native Method) 
	at com.fengdonghao.java.DemoThread.run(InterruptedDemo1.java:26) 
sub-isInterrupted:false 
sub-isInterrupted:false 
sub-isInterrupted:false 
。。。 

当main sleep前,查询demo线程的中断状态是 false (未中断),main sleep 0.5s之后,demo线程执行interrupt方法,随即在main中查询demo线程的中断状态为true,此时可以看到demo线程并没有直接中断,而是在一直执行。
问题来了,为什么demo线程中,查询该线程的中断状态是false,而不是true,不是刚才执行了interrupt方法吗?原因是 查询Api得知
这里写图片描述

现在知道了interrupt方法并不能停掉线程,那么如何停止某个线程呢

class DemoThread extends Thread{ 
	@Override 
	public void run() { 
		try { 
			while(!Thread.currentThread().isInterrupted()){ 
				System.out.println("subThread--"+Thread.currentThread().isInterrupted()); 
				} 
			throw new InterruptedException(); 
		} catch (InterruptedException e) { 
//			e.printStackTrace(); 
			Thread.currentThread().interrupt(); 
		} 
	} 
} 
//结果 
main-isInterrupted:false 
subThread--false 
main-isInterrupted:true 
Main thread stopped. 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/17425.html

(0)
上一篇 2021年7月19日 20:11
下一篇 2021年7月19日 20:11

相关推荐

发表回复

登录后才能评论