【java并发】基础(2)--线程中断和终止

来源:互联网 发布:物理数据库模型图 编辑:程序博客网 时间:2024/05/29 16:32

一、线程中断

  interrupt()的作用是中断本线程。
  本线程中断自己是被允许的;其它线程调用本线程的interrupt()方法时,会通过checkAccess()检查权限。这有可能抛出SecurityException异常。
  如果本线程是处于阻塞状态:调用线程的wait(), wait(long)或wait(long, int)会让它进入等待(阻塞)状态,或者调用线程的join(), join(long), join(long, int), sleep(long), sleep(long, int)也会让它进入阻塞状态。若线程在阻塞状态时,调用了它的interrupt()方法,那么它的“中断状态”会被清除并且会收到一个InterruptedException异常。
  如果不属于前面所说的情况,那么通过interrupt()中断线程时,它的中断标记会被设置为“true”。
  中断一个“已终止的线程”不会产生任何操作。

二、线程终止

2.1 Java中如何停止一个线程?

  Java并没有为停止线程提供API。
  JDK 1.0本来有一些像stop(), suspend() 和 resume()的控制方法,但是由于潜在的死锁威胁因此在后续的JDK版本中被弃用了;
  之后Java API的设计者就没有提供一个兼容且线程安全的方法来停止一个线程。当run() 或者 call() 方法执行完的时候线程会自动结束;如果要手动结束一个线程,可以用volatile 布尔变量来退出run()方法的循环或者是取消任务来中断线程。

2.2 过期的stop()、suspend()和resume()

  不建议使用的原因主要是:以suspend()方法为例,在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。同样,stop()方法在终结一个线程时不会保证线程的资源正常释放,通常是没有给予线程完成资源释放工作的机会,因此会导致程序可能工作在不确定状态下。

2.3 安全地终止线程

2.3.1 终止处于“阻塞状态”的线程

  通常,我们通过“中断”方式终止处于“阻塞状态”的线程。
  当线程由于被调用了sleep(), wait(), join()等方法而进入阻塞状态,若此时调用线程的interrupt()将线程的中断标记设为true。由于处于阻塞状态,中断标记会被清除,同时产生一个InterruptedException异常。将InterruptedException放在适当的为止就能终止线程。

public class StopByInterrupt {    public static void main(String[] args) {        Thread myThread = new MyThread();        myThread.start();        myThread.interrupt();    }}class MyThread extends Thread{    @Override    public void run() {        try{            while(true){                Thread.sleep(10);            }        }catch(InterruptedException e){            e.printStackTrace();            System.out.println("StopByInterrupt");        }    }}

2.3.2 终止处于“运行状态”的线程

使用flag终止运行中的线程:
* isInterrupted()
* volatile布尔变量

/** * 安全地终止线程: * 2.使用flag终止运行中的线程 * 2.1 isInterrupted() * 2.2 volatile布尔变量 * @author lc 2017/4/25 */public class StopByFlag {    public static void main(String[] args) throws Exception {    // 2.1 isInterrupted()        Runnable runner1 = new MyRunner();        Thread thread1 = new Thread(runner1);        thread1.start();        //main线程睡眠一秒,让thread1运行一会再使用interrupt()修改中断标记        TimeUnit.SECONDS.sleep(1);        //注意:interrupt()并不会终止处于“运行状态”的线程!它只是将线程的中断标记设为true。        thread1.interrupt();    //2.2 volatile布尔变量          Runnable runner2 = new MyRunner();        Thread thread2 = new Thread(runner2);        thread2.start();        //main线程睡眠一秒,让thread2运行一会再调用cancel修改on变量        TimeUnit.SECONDS.sleep(1);        ((MyRunner) runner2).cancel();//Runnable接口中没有cancel方法    }}class MyRunner implements Runnable{    private long i=0; //i有可能很大,long    private volatile boolean on = true;    @Override    public void run() {        while(on&&!Thread.currentThread().isInterrupted()){            i++;        }        System.out.println(i);    }    public void cancel(){        on=false;    }}

2.3.3 综合的形式

@Overridepublic void run() {    try {        // 1. isInterrupted()保证,只要中断标记为true就终止线程。        while (!isInterrupted()) {            // 执行任务...        }    } catch (InterruptedException ie) {          // 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。        }

参考资料

Java多线程系列–“基础篇”09之 interrupt()和线程终止方式
《Java并发编程的艺术》.第4章. 4.2启动和终止线程

0 0
原创粉丝点击