如何从Java中的另一个线程中杀死一个线程? [英] How do I kill a thread from another thread in Java?

查看:154
本文介绍了如何从Java中的另一个线程中杀死一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个主线程调用两个线程,称它们为线程1和线程2.当线程1停止时,我也想停止或杀死线程2。我怎么能这样做呢?我想要的实际输出有一个变化。那就是有一个主类也是thread.From主类我调用thread1和thread2.I我从主类给出一个输入但是当这个输入被改变时我想杀死正在运行的thread1并再次用另一个输入启动它。第二个线程,thread2将运行thread1给出的输出。所以当第一个线程被杀死时,第二个线程将被运行但是只有当t6是该线程的输入时才会给出输出。

I am calling two threads from a main thread, call them thread 1 and thread 2. When thread 1 stops, I want to stop or kill thread 2 also. How can I do this?There is a change in actual output what i want.That is There is a main class which is also thread.From main class i am calling thread1 and thread2.I am giving an input to thread1 from main class but when this input is getting changed i want to kill the running thread1 and start it once again with another input.The second thread,thread2 will run with the output given by the thread1.So eventually when the first thread is killed the second will be running but will give an output only if t6here is an input for that thread.

推荐答案

Java已经弃用了显式杀死另一个线程的方法(像Thread.stop / Thread.destroy)。正确的方法是确保另一个线程上的操作可以处理被告知停止(例如,他们期望一个InterruptedException,这意味着你可以调用Thread.interrupt()来阻止它。)

Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).

您可能还有兴趣将第二个线程设置为守护程序线程,这意味着如果VM中的所有其他线程都已完成,则进程将退出。

You might also be interested in setting the second thread as a daemon thread, which means that in case all other threads in the VM have finished then the process will exit.

这篇关于如何从Java中的另一个线程中杀死一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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