0
我试图实现一些逻辑,当我创建主(父)线程女巫执行其他线程。然后它等待一些子线程创建的条件。条件满足后,父亲执行一些更多的子线程。 当我使用等待/通知我有java.lang.IllegalMonitorStateException异常的问题。下面是代码:线程与ThreadPoolExecutor同步
public class MyExecutor {
final static ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10);
final static ExecutorService svc = Executors.newFixedThreadPool(1);
static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 8, 10, TimeUnit.SECONDS, queue);
public static void main(String[] args) throws InterruptedException {
final MyExecutor me = new MyExecutor();
svc.execute(new Runnable() {
public void run() {
try {
System.out.println("Main Thread");
me.execute(threadPool, 1);
System.out.println("Main Thread waiting");
wait();
System.out.println("Main Thread notified");
me.execute(threadPool, 2);
Thread.sleep(100);
threadPool.shutdown();
threadPool.awaitTermination(20000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
svc.shutdown();
svc.awaitTermination(10000, TimeUnit.SECONDS);
System.out.println("Main Thread finished");
}
public void execute(ThreadPoolExecutor tpe, final int id) {
tpe.execute(new Runnable() {
public void run() {
try {
System.out.println("Child Thread " + id);
Thread.sleep(2000);
System.out.println("Child Thread " + id + " finished");
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
当我评论的等待和通知行,我有以下的输出:
主线
主线程等待
主线程通知
子线程1
子线程
子线程1完成
子线程2完成
主线程完成
+1我试图找出一种方法来解释给他们,因为提供的代码是如此的不合时宜。 – 2011-03-20 16:24:49
谢谢。它正在与同步(svc)工作{ \t \t \t \t \t svc.notify(); \t \t \t \t \t} – BigWonder 2011-03-20 16:45:26
@Brian Roach:不幸的是'wait/notify'结构非常脆弱和冗长,很多地方犯了一个错误。 @ justme1考虑使用一些专用对象('final Object lock = new Object()')来锁定或锁定MyExecutor(当你摆脱所有静态的时候)。请接受我们两人的利益答案:-)。 – 2011-03-20 16:59:40