class WorkerThread {
Semaphore sem;
void checkForPause() throws InterruptedExec{
synchronized(sem) { // make sure unpauseThread() cant release it
sem.aquire(); // will block when pauseThread aquired one
sem.release();
}
}
void pauseThread() {
sem.aquire();
}
void unpauseThread() {
synchronized(sem) { sem.release(); } // only release after checkForPause()
}
work run() {
while(true) { // do something in a loop
checkForPause();
// do actual work in small steps
}
}
}
# 1 楼答案
Java中没有对线程的细粒度控制。您通常会尝试避开线程优先级,因为它会生成脆弱的系统。但是,如果您必须这样做,您可以更改线程优先级,大多数系统都会考虑它
只有当其他线程确实支持此功能时,才能暂停它们。但请记住,暂停的线程仍然会占用所有内存和资源。暂停和恢复一个线程所需的工作可能不会以收益为理由。(在这方面,优先事项更好)
例如,要暂停线程,可以使用工作线程中获得的锁。无论何时(被更重要的线程)锁定,它都会使工作线程暂停(没有CPU使用)
现在可以使用pauseThread()和unpauseThread()控制WorkerThread实例
顺便说一句:在旧的Java中有
Thread#suspend()
和Thread#resume()
,但不应该在现代程序中使用。在deprecation notice中有一些替代代码# 2 楼答案
您需要使用线程的类join()方法
假设有两个线程T1和T2。 当您调用
T1.start()
、T1.join()
并调用T2.start()
时,T1将等待T2完成它的工作,然后T1将执行请通过以下链接了解更多详细信息
Thread join() method