如何在Java中启动/停止/重启线程? [英] How to start/stop/restart a thread in Java?

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

问题描述

我很难找到一种在Java中启动,停止和重启线程的方法。

I am having a real hard time finding a way to start, stop, and restart a thread in Java.

具体来说,我有一个类任务(目前在文件 Task.java 中实现 Runnable )。我的主应用程序需要能够在一个线程上启动此任务,在需要时停止(终止)该线程,有时甚至是KILL&重新启动线程...

Specifically, I have a class Task (currently implements Runnable) in a file Task.java. My main application needs to be able to START this task on a thread, STOP (kill) the thread when it needs to, and sometimes KILL & RESTART the thread...

我的第一次尝试是使用 ExecutorService 但我似乎无法找到方法为它重新启动任务。当我使用 .shutdownnow()以后对 .execute()的任何调用都会失败,因为 ExecutorService 是关闭......

My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow() any future call to .execute() fails because the ExecutorService is "shutdown"...

那么,我怎么能做到这一点?

So, how could I accomplish this?

推荐答案

一旦线程停止,您就无法重新启动它。但是,没有什么可以阻止您创建和启动新线程。

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

选项1:创建新线程而不是尝试重新启动。

Option 1: Create a new thread rather than trying to restart.

选项2:不要让线程停止,让它等待,然后当它收到通知时,你可以让它再次工作。这样线程永远不会停止,永远不需要重新启动。

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

根据评论进行编辑:

要杀死线程,您可以执行以下操作。

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

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

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