我在尝试在经过一段时间后立即停止线程时遇到问题,因为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?
}
}
}
});
}
答案 0 :(得分:2)
您需要为扩展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...
最后两条消息在时间上几乎相等,可能会改变位置(两个不同的线程,继续)
答案 1 :(得分:0)
Java已经弃用了显式杀死另一个线程的方法(比如Thread.stop / Thread.destroy)。正确的方法是确保另一个线程上的操作可以处理被告知停止(例如,他们期望一个InterruptedException,这意味着你可以调用Thread.interrupt()来阻止它。)
答案 2 :(得分:0)
杀死/停止线程是一个坏主意。这就是他们弃用这些方法的原因。最好要求线程停止。例如,类似下面的例子。 (但请注意:如果“do_something()”需要很长时间,那么您可能希望使用中断来中止它。)
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;
}
}