我遇到的情况是我需要阻止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();
}
}
答案 0 :(得分:0)
执行此操作的唯一正确方法是cancel
与您的任务相对应的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);
答案 1 :(得分:-1)
自愿停止线程并不是一个好主意。您的代码没有停止一个实际阻止整个JVM表单进一步发展的线程。你实际上错过了执行者服务的全部内容。
遗嘱执行人的意识形态是“我&#39;有一个扩展/收缩的线程列表,将为您完成工作。 &#39;你&#39;只需给我个人的,互相排斥的工作岗位(Runnables或Callables)。这里要理解的主要问题是&#34;你不必担心线程及其生命周期&#34; ...你只是创建工作项目并让他们执行。如果您不想执行某项作品或想要停在中间,请拨打cancel
方法,否则请不要担心,因为一旦完成,我就会“#I&#39;将完成并清理并提供返回值(如果有的话)。
&#39;我&#39;还将为您管理线程池,但是当工作作业进入速度更快时将其扩展为更多线程,并通过&#34;关闭空闲线程&#34;当工作不那么频繁地涌入。
现在告诉我,你正在努力实现的目标是正确的。
答案 2 :(得分:-1)
尝试thread.interrupt()
,但 不推荐 。
答案 3 :(得分:-1)
您可以将Quasar库用于线程,比Java本机线程更快地运行并且更易于使用。 http://www.paralleluniverse.co/quasar/
答案 4 :(得分:-2)
你可以使用thread.stop
,虽然它会抛出需要处理的threadDeathError。
如果你使用future.cancel
,它将取消任务但不会杀死线程,因为线程将返回线程池。 Thread.stop
会杀死该帖子。