假设我有 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
}
}