[英]java: do not start another thread while current alive
我有方法“开始”的主线程。 此方法启动另一个线程,该线程需要很长时间。 可以从另一个线程调用方法“ start”。 如果已经有一个正在运行并且不锁定主线程,如何避免在“启动”方法中创建新线程? 我尝试使用singleThreadExecutor,但是它使任务排队。
代码:启动方法:
public void start(){
// need only one active thread
// if thread alive, avoid to start another
t = new Thread( new Runnable() {
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
简单测试
for (int i = 0; i < 100; i++) {
Thread r = new Thread( new Runnable() {
public void run() {
Helper.getInstance().start();
}
});
r.start();
}
如果只想在当前线程繁忙时丢弃新任务,则可以使用SingleThreadExecutor并将其配置为丢弃所有溢出任务,而不是对其进行排队。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.