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

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

问题描述

我真的很难找到在 Java 中启动、停止和重新启动线程的方法.

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

具体来说,我在文件 Task.java 中有一个类 Task(当前实现了 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天全站免登陆