gpt4 book ai didi

java - 使用 ThreadPoolExecutor 进行线程同步

转载 作者:行者123 更新时间:2023-12-01 07:40:39 25 4
gpt4 key购买 nike

当我创建主(父)线程并执行其他几个线程时,我试图实现一些逻辑。然后它等待子线程创建的某些条件。条件满足后,父亲执行更多的子线程。当我使用 wait/notify 时出现 java.lang.IllegalMonitorStateException 异常的问题。这是代码:

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
子线程2
子线程 1 已完成
子线程 2 完成
主线程完成

最佳答案

您的代码中存在一系列设计缺陷:

<小时/>

仅当您是对象锁的所有者时,才必须调用 wait()notify():

synchronized(foo) {
foo.wait();
}
<小时/>

您正在不同的对象(内部类!)上调用 wait()notify() - 如果一个线程正在等待一个对象,则必须调用 通知相同对象。

<小时/>

当出现以下情况时,有可能会错过通知:

me.execute(threadPool, 1);

wait之前调用 - 非常严重的错误(竞争条件可能性)。

其他人可能会建议您使用一些更高级别的同步方法,但了解基础知识至关重要。

关于java - 使用 ThreadPoolExecutor 进行线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com