【发布时间】:2021-03-29 13:48:52
【问题描述】:
我有 2 个工作线程和 1 个处理线程。
当处理线程试图处理某事并且工作线程正在执行它们的工作时,处理线程应该等待,并在工作线程中完成的所有工作完成后唤醒。
我怎样才能唤醒这个线程?我将尝试在此伪代码中演示我的意思
class Worker{
/... variables ../
private final Condition condition;
public Worker(Condition condition){
// constructor
}
public void start(){
Thread thread = new Thread(this::run);
thread.start();
}
private void run(){
try{
...
condition.signalAll();
}
}
}
和处理线程类似
class Processing{
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void start(){
Worker worker1 = new Worker(condition);
Worker worket2 = new Worker(condition);
worker1.start();
worker2.start();
// some code //
while( // some flag indicating that workers are doing something){
condition.await();
}
// this should be processed only after both worker1 and worker2 called signalAll
}
}
这样的事情可能吗?让线程等待多个源调用 notifyAll() 而不仅仅是一次。我希望我清楚地构建了这个问题。
感谢您的帮助!
【问题讨论】:
标签: java multithreading parallel-processing synchronization