如何在Java中停止不间断线程 [英] How to stop uninterruptible threads in Java

查看:109
本文介绍了如何在Java中停止不间断线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 我无法编辑 的Java应用程序启动 java.lang.Thread 有这个 run()方法:

I have a Java application that I CAN'T EDIT that starts a java.lang.Thread that has this run() method:

public void run(){
   while(true){
     System.out.println("Something");
   }
}

在某个时间点我想阻止它。如果我使用 Thread.interrupt()它不起作用。
如果我使用 Thread.stop()它可以工作,但不推荐使用此方法(因此不鼓励使用它,因为它可能会在新版本中从JVM中删除) 。

At a certain point in time I want to stop it. If I use Thread.interrupt() it doesn't work. If I use Thread.stop() it works, but this method is deprecated (so its use is discouraged as it may be removed from JVM in new releases).

如何在Java中停止此类不间断线程?

How to stop such uninterruptible threads in Java?

推荐答案

您可以使用检查变量实现中断方法。

You can implement the interrupt method using a check variable.

首先使用volatile变量变量:

First of all use a volatile check variable as:

volatile boolean tostop = false; // Keep the initial value to be false

接下来定义要依赖此变量的线程。

Next define your thread to be dependent to this variable.

Thread thread1 = new Thread(){
    public void run() {
        while(!tostop) {
         -- Write your code here --
        }
     }
 }

接下来定义使用该线程的函数:

Next define the function in which to use the thread:

public void ....{
    //Interrupt code
    tostop = true;
    thread1.sleep(300);  // Give the thread sometime for cleanup
    //Use System.exit(0), if the thread is in main function.
}

希望这有帮助。

这篇关于如何在Java中停止不间断线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆