java - 停止执行程序服务中的线程

标签 java multithreading

我遇到了需要停止运行 Executor 服务线程的情况。

我已经阅读了其他帖子中的解决方案,其中提到使用 Future 对象并取消任务。

但我宁愿尝试不同的方法。

如果这种方法有任何问题,谁能告诉我。

以下是我的 Runnable 类。

public class TestRunnable implements Runnable {     
    Thread t;
    @Override
    public void run() {
        // TODO Auto-generated method stub

        setT(Thread.currentThread());

        while(true)
        {
            if(Thread.currentThread().isInterrupted())
            {
                System.out.println("From Inside thread, Exiting");
                System.exit(0);
            }
        }
    }

    public void setT(Thread t) {
        this.t = t;
    }

    public Thread getT() {
        return t;
    }
}

以下是我的主要方法:

import java.io.IOException;    
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 

public class ruunTest {    
    public static void main(String[] args) throws IOException,     InterruptedException {    
        // TODO Auto-generated method stub    

        ExecutorService service = Executors.newCachedThreadPool();  

        TestRunnable test = new TestRunnable(); 

        service.execute(test);    

        Thread.sleep(1000);            
        System.out.println("About to Interrupt");     

        test.getT().interrupt();  
    }           
}

最佳答案

唯一正确的做法是取消你的任务对应的Future,在你的任务中,你应该定期检查线程是否被中断.

类似的东西:

public class Task implements Callable<Void> {
    @Override
    public Void call() throws InterruptedException {
        while(true) {
            // Check regularly in your code if the thread has been
            // interrupted and if so throws an exception to stop
            // the task immediately 
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException("Thread interrupted");
            }
        }
    }
}

那么你的主要代码是:

ExecutorService service = Executors.newCachedThreadPool();
// My task
Task task = new Task();
// Submit the task and get the corresponding future
Future<?> future = service.submit(task);
...
// Cancel the task which will interrupt the thread that was executing the 
// task if any
future.cancel(true);

关于java - 停止执行程序服务中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37983867/

相关文章:

java - matlab 日期字符串在 python scipy.io 中生成 java lang 字符串

java - 在企业网络中解锁防火墙以访问 Google 文本转语音 API 需要什么 URL?

java - classNotFoundException GWTBridge 类

multithreading - "Spawn a thread"类似 node.js 中的行为

c# - 从 TimerCallback 函数更新 UI 线程 Windows Phone 8

C线程调度(和asm)

c - Pthreads 堆栈优先级

java - 使用sun HttpsServer时如何获取ssl session

java - 从 java 应用程序中获取用户名 (windows)

python - 为什么我在 Python 中的线程化 MySQLdb 查询比相同的非线程化查询慢?