我已经四处寻找了一段时间,检查了池、执行器和 future 的一些实现,但它们都不符合我的目的......或者至少我无法正确实现它。
我有一个类库,全部类似于:
class X implements Runnable {
@Override
public void run() {
// do sth
}
}
我无法修改它们。
还有我的类(class):
class Controller {
private int threadState;
void threadStart() {
// run a thread (made from any of the classes above)
// and when it exits change the threadState value to V
}
}
我需要的只是在threadStart()中运行一个线程,它会在退出后执行一些操作,但threadStart()函数应该立即通过。
您有什么好主意可以用 Java 或/和 Groovy 解决这个问题吗?谢谢。
最佳答案
实现此目的的一种可能(但有点丑陋)的方法是在执行之前将您的任务包装在另一个可运行程序中。包装器将负责委托(delegate)实际任务,并在完成时调用回调方法:
void changeThreadState() {
// This is your call back, in controller
}
void threadStart() {
final X task = new X(); // task creation (variable has to be final)
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
task.run();
changeThreadState();
}
});
t.start();
}
您当然会添加异常处理和所有此类好东西。
请注意,与直接在 threadStart
方法中创建线程相反,您还可以使用 Executor 或任何其他类型的线程池构造。
关于Java/Groovy 线程退出操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15585699/