gpt4 book ai didi

java - 如何在超过一定时间后立即停止线程?

转载 作者:行者123 更新时间:2023-11-30 04:03:48 25 4
gpt4 key购买 nike

我在尝试在一段时间过后立即停止线程时遇到问题,因为 thread.stop 和类似的其他线程已被贬值。

我试图停止的线程使用我的鼠标,我需要停止它,以便我可以以其他方式使用我的鼠标。

我想到的是下面的代码,这只是为了创建另一个线程来观察主线程运行了多长时间,如果它还活着,则停止它,但我不能完成这个。

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 及其 awaitTermination(long timeout, TimeUnit unit) 方法。 (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html)

将节省大量工作。

    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 - 如何在超过一定时间后立即停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com