停止线程

一、停止线程

  停止线程是在多线程开发时很重要的技术点,掌握此技术可以对线程的停止进行有效的处理。停止线程在Java语言中并不像break语句那样干脆,需要一些技巧性的处理。
  使用Java内置支持多线程的类设计多线程应用是很常见的事情,然而,多线程给开发人员带来了一些新的挑战,如果处理不好就会导致超出预期的行为并且难以定位错误。
  停止一个线程意味着在线程处理完任务之前停掉正在做的操作,也就是放弃当前的操作。虽然这看起来非常简单,但是必须做好防范措施,以便达到预期的效果。
  
  在Java中有以下3种方法可以终止正在运行的线程:
  1).使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2).使用stop方法强行终止线程,但是不推荐使用这个方法,因为stop和suspend及resume一样,都是作废过期的方法,使用它们可能产生不可预料的结果。
  3).使用interrupt方法中断线程。尽管方法的名称是“停止,中止”的意思,但这个方法不会终止一个正在运行的线程,还需要加入一个判断才可以完成线程的停止。
  4).异常法

方法stop已经被作废,因为如果强制让线程停止则有可能使一些清理性的工作得不到完成。另外一个清况就是对锁定的对象进行了“解锁”,导致数据得不到同步的处理,出现数据不一致的问题。

1、使用退出标志

// 线程类
public class MyThread5 extends Thread{
    // ,这个关键字的目的是使exit同步,也就是说在同一时刻只能由一个线程来修改exit的值
    public volatile boolean exit = false;

    public void run() {
        int i = 0;
        while (!exit) {
            System.out.println("i: " + i++);
        }
        System.out.println("线程没停止,只是退出了循环");
    }
}

// 测试类
public class StopThreadTest {
    public static void main(String[] args) {
        try {
            //5.停止线程5--使用退出标志
            MyThread5 thread5 = new MyThread5();
            thread5.start();

            Thread.sleep(1000); // 主线程延迟1秒

            thread5.exit = true;  // 终止线程thread
            // thread5.join(); //没有join,不会输出线程退出
            System.out.println("使用退出标志--线程退出!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  在上面代码中定义了一个退出标志exit,当exit为true时,while循环退出,exit的默认值为false.在定义exit时,使用了一个Java关键字volatile,这个关键字的目的是使exit同步,也就是说在同一时刻只能由一个线程来修改exit的值,

2.使用interrupt方法
1、interrupt()方法停止不了的线程
  本示例将调用interrupt()方法来停止线程,但interrupt方法的使用效果并不像for+break语句那样,马上就停止循环。调用interrupts方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程。
示例如下:

public class MyThread2 extends Thread{
    public MyThread2(String name) {
        super(name);
    }

    public void run() {
        super.run();

        //用for循环不能达到想要的结果
        for (int i=0; i < 100000; i++) {
            System.out.println("i=: " + i+1);
        }
    }
}

class Test2 {
    public static void main(String[] args) {
        MyThread2 thread2 = new MyThread2();
        thread2.start();
        try {
            Thread.sleep(2000);
            //不会中断正在执行的线程,原因是因为interrupt()方法只设置中断状态标志位为true
            thread2.interrupt();  
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}

  会输出所有的结果,从运行结果来看,调用 Interrupt方法并没有停止线程。

2、判断线程是否是停止状态的两个方法
  在介绍如何停止线程的知识点前,先来看一下如何判断线程的状态是不是停止的。在Java的SDK中,Thread.java类里提供了两种方法。
1)this.interrupted():测试当前线程是否已经中断。
  方法声明: public static boolean interrupted()
2)this.isInterrupted():测试线程是否已经中断。
  方法声明: public boolean isInterrupted() 不是静态的

2.1.interrupted()
  那么这两个方法有什么区别呢?先来看看this.interrupted()方法的解释:测试当前线程是否已经中断,当前线程是指运行this.interrupted()方法的线程。为了对此方法有更深入的了解,示例代码如下:

public class MyThread2 extends Thread{
    public void run() {
        super.run();
        for (int i = 0; i< 3; i++) {
            System.out.println("i= " + (i+1));
        }
    }
}

class Test2 {
    public static void main(String[] args) {
        MyThread2 thread2 = new MyThread2();
        thread2.start();
        try {
            Thread.sleep(2000);
            thread2.interrupt();  

            System.out.println("是否停止1? ="+thread2.interrupted());
            System.out.println("是否停止2? ="+thread2.interrupted());
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }

        System.out.println("end!");
    }
}

i= 1
i= 2
i= 3
是否停止1? =false
是否停止2? =false
end!
  这也证明了interrupted方法的解释:测试当前线程是否已经中断。这个“当前线程”是main,它从未中断过,所以打印的结果是两个false.

class Test3 {
    public static void main(String[] args) {
        Thread.currentThread().interrupt();  //  当前线程中断

        System.out.println("是否停止1? ="+Thread.interrupted());
        System.out.println("是否停止2? =" + Thread.interrupted());
        System.out.println("end");
    }
}

是否停止1? =true
是否停止2? =false
end
  从上述的结果来看,方法interrupted()的确判断出当前线程是否是停止状态。但为什么第2个布尔值是false呢?查看一下官方帮助文档中对interrupted方法的解释:

测试当前线程是否已经中断。线程的中断状态由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。

  文档已经解释得很详细,interrupted()方法具有清除状态的功能,所以第2次调用interrupted()方法返回的值是false.

2.2.isInterrupted()
  介绍完interruptedn方法后再来看一下isInterrupted()方法,声明如下:
public boolean isInterrupted()
  从声明中可以看出isInterrupted方法不是static的。
  
  最后,再来看一下这两个方法的解释。
  1). this.interrupted():测试当前线程是否已经是中断状态,执行后具有将状态标志置清除为false的功能。
  2).this.isInterrupted():测试线程Thread对象是否已经是中断状态,但不清除状态标志。
  
3、异常法
  有了前面学习过的知识点,就可在线程中用for语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可。示例如下

public class MyThread3 extends Thread{
    public void run() {
        super.run();
        while (true) {
            if (interrupted()) {
                System.out.println("停止了");
                break;
            }
            System.out.println("timer: " + System.currentTimeMillis());
        }

        system.out.println("我在循环下面");
    }
}

class Test3 {
    public static void main(String[] args) {
        MyThread3 thread3 = new MyThread3();
        thread3.start();

        try {
            Thread.sleep(1000);
            thread3.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }

        System.out.println("end");
    }
}

……
timer: 1462246520430
timer: 1462246520626
timer: 1462246520626
end
停止了
我在循环下面

  如何解决语句继续运行的问题,把break改为 throw new InterruptedException(); 或者return;就行
  不过还是建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止的事件得以传播。
  
4、sleep()
如果线程在sleep()状态下停止线程,会是什么效果呢?

public class MyThread extends Thread{
    //继承Thread需要重写run方法
    public void run() {
        super.run();
        for (int i=0; i<1000;i++) {
            System.out.println("i= " + (i+1));
        }
        System.out.println("run begin");
        try {
            Thread.sleep(5000);
            System.out.println("run end");  // 这个没有输出
        } catch (InterruptedException e) {
            System.out.println("在sleep中先停止,再进入catch!  " + this.isInterrupted());
            e.printStackTrace();
        }
    }
}

class TestThread {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        myThread.interrupt();
        System.out.println("运行结束!");
    }
}

i= 998
i= 999
i= 1000
run begin
在sleep中先停止,再进入catch! false
java.lang.InterruptedException: sleep interrupted

  从打印的结果来看,如果在sleep状态下停止某一线程,会进入catch语句,并且清除停止状态值,使之变成false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值