假设我有3个执行线程,下面描述每个线程将执行的操作。
线程1 - 主线程 线程2 - 探测器线程 线程3 - 动作线程
当线程1启动时,它会生成线程2.线程2将与线程1一起运行并搜索事件。当事件发生时,我希望线程2生成一个新线程,线程3.我希望线程3与线程1连接。这可能吗?
示例代码:
public class ThreadA {
// variable to flag if ThreadB should still loop
private static boolean runThreadB = true;
public void mainMethod() {
new ThreadB().start();
// do some stuff
// make sure thread B can end
runThreadB = false;
}
// inner class / Thread B
class ThreadB extends Thread {
@Override
public void run() {
// loop until Thread A is done
while (runThreadB) {
// wait for event, if event is found, spawn thread C
ThreadC threadC = new ThreadC();
threadC.start();
/**
* Need thread C to somehow join ThreadA
*/
try {
threadC.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class ThreadC extends Thread {
@Override
public void run() {
// perform some tasks
}
}
答案 0 :(得分:1)
您必须同步线程。您可以使用ReentrantLock
执行此操作。
以下是您的问题的简单示例(事件生产者 - 消费者):
public class Foo{
//...
public void consumeEvent() throws InterruptedException{
aLock.lock();
try {
while(noEvent){
eventAvailable.await();
}
// use the event
} finally {
sLock.unlock();
}
}
public void createEvent() throws InterruptedException{
aLock.lock();
try {
// add an event
eventAvailable.signalAll();
} finally {
sLock.unlock();
}
}
private Lock aLock = new ReentrantLock();
private Condition eventAvailable = aLock.newCondition();
}
您的主题将使用此类中的对象。
Thread eventProducer = ...
Thread eventConsumer = ...
eventProducer.start();
eventConsumer.start();
您的线程现在已同步。