Java 如何在一定时间到期后立即停止线程?
在经过一定的时间后,我在尝试立即停止一个线程时遇到了问题,因为thread.stop和其他类似的线程已经贬值 我试图停止的线程使用了我的鼠标,我需要停止它,以便我可以以其他方式使用我的鼠标 我想的是下面的代码,它只是让另一个线程来观察主线程运行了多长时间,如果它还活着,就停止它,但我无法完成这一点Java 如何在一定时间到期后立即停止线程?,java,multithreading,Java,Multithreading,在经过一定的时间后,我在尝试立即停止一个线程时遇到了问题,因为thread.stop和其他类似的线程已经贬值 我试图停止的线程使用了我的鼠标,我需要停止它,以便我可以以其他方式使用我的鼠标 我想的是下面的代码,它只是让另一个线程来观察主线程运行了多长时间,如果它还活着,就停止它,但我无法完成这一点 public void threadRun(int a) { Thread mainThread = new Thread(new Runnable() { @Override
public void threadRun(int a) {
Thread mainThread = new Thread(new Runnable() {
@Override
public void run() {
// does things with mouse which may need to be ended while they
// are in action
}
});
Thread watchThread = new Thread(new Runnable() {
@Override
public void run() {
if (timeFromMark(mark) > a) {
if (mainThread.isAlive()) {
// How can I stop the mainThread?
}
}
}
});
}
您需要为扩展runnable的第二个线程定义一个类,并将第一个线程作为参数传递 然后可以停止第一个线程 但是,不要手动执行此操作,而是查看Java ThreadPoolExecuter及其
等待终止(长超时,时间单位)
方法。()
这将节省大量工作
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable r = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("doing stuff");
Thread.sleep(10000);
System.out.println("finished");
} catch (InterruptedException e) {
System.out.println("Interrupted before finished!");
}
}
};
executor.execute(r);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
} catch (InterruptedException e) {
//
}
System.out.println("Thread worker forced down. Continue with Application...");
产生:
doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...
最后两条消息在时间上几乎相等,并且可能会改变位置(它的两个不同线程,继续)Java有不推荐的显式终止另一个线程的方法(如thread.stop/thread.destroy)。正确的方法是确保另一个线程上的操作能够处理被告知停止的操作(例如,它们期望InterruptedException,这意味着您可以调用thread.interrupt()来停止它)
摘自杀死/停止线程是个坏主意。这就是为什么他们不赞成这些方法。最好让线程停止。例如,类似下面的例子。(但请注意:如果“dou_something()”需要很长时间,那么您可能需要使用中断来中止它。)
mainThread
是否可以监视自身并在给定时间后退出?我似乎无法正确配置此功能…我只能实现runnable,而执行器没有编译。不过,我想我找到了另一种方法,谢谢。
import java.util.concurrent.atomic.AtomicBoolean;
public class Stoppable {
private AtomicBoolean timeToDie = new AtomicBoolean(false);
private Thread thread;
public void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(new Runnable() {
public void run() {
while (!timeToDie.get()) {
// do_something();
}
}
});
thread.start();
}
public void stop() throws InterruptedException {
timeToDie.set(true);
thread.join();
thread = null;
}
}