Java终止线程的三种方式

3 篇文章 0 订阅

Java终止线程的三种方式:

1、线程正常退出,也就是当 run() 方法完成后线程中止。
2、使用 stop()> 方法强行终止线程,但是不推荐使用这个方法,该方法已被弃用。
3、使用 interrupt> 方法中断线程,在当前线程中打一个停止的标记,并不是真的停止线程。

一、线程正常退出

在 run() 方法执行完毕后,该线程就终止了。但是在某些特殊的情况下,run() 方法会被一直执行;

在服务端程序中可能会使用 while(true) { … }
这样的循环结构来不断的接收来自客户端的请求。此时就可以用修改标志位的方式来结束 run() 方法。

public class ServerThread extends Thread {
    //volatile修饰符用来保证其它线程读取的总是该变量的最新的值
    public volatile boolean exit = false; 

    @Override
    public void run() {
        ServerSocket serverSocket = new ServerSocket(8080);
        while(!exit){
            serverSocket.accept(); //阻塞等待客户端消息
            ...
        }
    }
    
    public static void main(String[] args) {
        ServerThread t = new ServerThread();
        t.start();
        ...
        t.exit = true; //修改标志位,退出线程
    }
}

二、 使用 stop() 终止线程

通过查看 JDK 的 API,我们会看到 java.lang.Thread 类型提供了一系列的方法如 start()、stop()、resume()、suspend()、destory()等方法来管理线程。但是除了 start() 之外,其它几个方法都被声名为已过时(deprecated)。

虽然 stop() 方法确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且该方法已被弃用,最好不要使用它。
JDK 文档中还引入用一篇文章来解释了弃用这些方法的原因:《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?》

为什么弃用stop:

调用 stop() 方法会立刻停止 run() 方法中剩余的全部工作,包括在 catch 或 finally 语句中的,并抛出ThreadDeath异常(通常情况下此异常不需要显示的捕获),因此可能会导致一些清理性的工作的得不到完成,如文件,数据库等的关闭。
调用 stop() 方法会立即释放该线程所持有的所有的锁,导致数据得不到同步,出现数据不一致的问题。

例如,存在一个对象 u 持有 ID 和 NAME 两个字段,假如写入线程在写对象的过程中,只完成了对 ID 的赋值,但没来得及为 NAME 赋值,就被 stop() 导致锁被释放,那么当读取线程得到锁之后再去读取对象 u 的 ID 和 Name 时,就会出现数据不一致的问题。

三. 使用 interrupt() 中断线程

现在我们知道了使用 stop() 方式停止线程是非常不安全的方式,那么我们应该使用什么方法来停止线程呢?答案就是使用 interrupt() 方法来中断线程。

需要明确的一点的是:
interrupt() 方法并不像在 for 循环语句中使用 break 语句那样干脆,马上就停止循环。调用 interrupt() 方法仅仅是在当前线程中打一个停止的标记,并不是真的停止线程。

也就是说,线程中断并不会立即终止线程,而是通知目标线程,有人希望你终止。至于目标线程收到通知后会如何处理,则完全由目标线程自行决定。这一点很重要,如果中断后,线程立即无条件退出,那么我们又会遇到 stop() 方法的老问题。

事实上,如果一个线程不能被 interrupt,那么 stop 方法也不会起作用。

我们来看一个使用 interrupt() 的例子:

public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i=0;i<3000;i++){
                System.out.println(i);
            }
            System.out.println("thread end");
        });
        thread.start();
        System.out.println("thread interrupt");
        thread.interrupt();
        System.out.println("thread interrupt...");
        try {
            System.out.println("main star to sleep 2s");
            Thread.sleep(2000);
            System.out.println("main sleep 2s end");
        } catch (InterruptedException e) {
            System.out.println("InterruptedException:"+e);
        }
        System.out.println("main end");
    }

从输出的结果我们会发现 interrupt 方法并没有停止线程 t 中的处理逻辑,也就是说即使 t 线程被设置为了中断状态,但是这个中断并不会起作用,那么该如何停止线程呢?

这就需要使用到另外一个与线程中断有关的方法:

public boolean Thread.isInterrupted() //通过检查标志位,判断是否被中断

所以如果希望线程 t 在中断后停止,就必须先判断是否被中断,并为它增加相应的中断处理代码:

Thread thread = new Thread(() -> {
    System.out.println("thread start");
    for (int i=0;i<3000;i++){
        if(Thread.currentThread().isInterrupted()){
            System.out.println("thread isInterrupted");
            break;
        }else {
            System.out.println(i);
        }
    }
    System.out.println("thread end");
});
thread.start();

在上面这段代码中,我们增加了 Thread.isInterrupted() 来判断当前线程是否被中断了,如果是,则退出 for 循环,结束线程。

这种方式看起来与之前介绍的“使用标志位终止线程”非常类似,但是在遇到 sleep() 或者 wait() 这样的操作,我们只能通过中断来处理了。

/**
 * Causes the currently executing thread to sleep (temporarily cease
 * execution) for the specified number of milliseconds, subject to
 * the precision and accuracy of system timers and schedulers. The thread
 * does not lose ownership of any monitors.
 *
 * @param  millis
 *         the length of time to sleep in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public static native void sleep(long millis) throws InterruptedException;

Thread.sleep() 方法会抛出一个 InterruptedException 异常,当线程被 sleep() 休眠时,如果被中断,这会就抛出这个异常。
(注意:Thread.sleep() 方法由于中断而抛出的异常,是会清除中断标记的。)

可通过以下代码感受下:

public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("thread start");
            try {
                System.out.println("thread sleep 1s");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("thread InterruptedException");
            }
            for (int i=0;i<3000;i++){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("thread isInterrupted");
                    break;
                }else {
                    System.out.println(i);
                }
            }
            System.out.println("thread end");
        });
        thread.start();
        try {
            System.out.println("main start to sleep 10ms");
            Thread.sleep(10);
            System.out.println("main sleep 10ms end");
        } catch (InterruptedException e) {
            System.out.println("InterruptedException:"+e);
        }
        System.out.println("thread interrupt");
//        thread.stop();
        thread.interrupt();
        System.out.println("thread interrupt...");
        try {
            System.out.println("main star to sleep 2s");
            Thread.sleep(2000);
            System.out.println("main sleep 2s end");
        } catch (InterruptedException e) {
            System.out.println("InterruptedException:"+e);
        }
        System.out.println("main end");
    }
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值