我已经读了很多有关使线程等待的消息,但是我什么都做不了。我已经阅读了有关等待,通知,加入,锁定...的文档,但是仍然找不到解决我的问题的方法。
我有我的主流和另一个流在后台(用户不与之交互,它只是自己做的事情)。然后,在主流中,用户将有可能使用某些功能,直到他退出程序。我想要的是,当用户选择使用某个功能时,后台中的流在此功能期间暂停,之后又重新启动。
我将在这里用“伪”代码解释它:
main(args[]){
new Thread(new Background(), "Background").start();
while (user don't quit){
//user choose a function
-> find a way to pause Background thread
chosenFunction();
-> find a way to unpause the Background thread
}
}
public class Background implements Runnable{
public Background(){}
public void run(){
while (thread is not paused){
//do some stuff
}
}
}
我不认为我应该使用join,因为我不想等待另一个线程的完成,而是等待另一个线程中的功能的完成。我以为锁是答案,但我无法使它起作用。我已经尝试过了:
main(args[]){
ReentrantLock lock = new ReentrantLock();
new Thread(new Background(lock), "Background").start();
while (user don't quit){
//user choose a function
lock.lock();
chosenFunction();
lock.unlock();
}
}
public class Background implements Runnable{
private final ReentrantLock lock;
public Background(ReentrantLock lock){
this.lock = lock;
}
public void run(){
while (!lock.islocked()){
//do some stuff
}
}
}
或搭配:
public void run(){
while(lock.isLocked){
sychronized(this){
wait();
}
}
//do some stuff
}
但这是行不通的。
如果需要更多上下文:后台线程正在等待套接字发出的消息,并且用户可以调用的功能也正在使用此套接字。是的,我的第一个想法是将该套接字作为两个流之间的同步对象,但是我也没有设法使其工作。
您可以使用volatile
变量。这是一个非常典型的volatile
变量用例。
public void main() {
BackgroundServiceThread bst = new BackgroundServiceThread();
bst.start();
while (true) {
//user choose a function
bst.isPaused = true;
chosenFunction();
bst.isPaused = false;
}
}
private static class BackgroundServiceThread extends Thread {
volatile boolean isPaused = false;
@Override
public void run() {
while (true) {
if (!isPaused) {
//do stuffs;
}
}
}
}
private void chosenFunction() {
//user choose function
}
当您在主线程中更新isPaused时,更改将立即在您的后台服务线程中可见,因为它是易变的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句