我正在编写将生成两个线程的代码,然后使用 CyclicBarrier 类等待它们同步。问题是循环屏障没有按预期工作,主线程没有等待各个线程完成。这是我的代码的样子:
class mythread extends Thread{
CyclicBarrier barrier;
public mythread(CyclicBarrier barrier) {
this.barrier = barrier;
}
public void run(){
barrier.await();
}
}
class MainClass{
public void spawnAndWait(){
CyclicBarrier barrier = new CyclicBarrier(2);
mythread thread1 = new mythread(barrier).start();
mythread thread2 = new mythread(barrier).start();
System.out.println("Should wait till both threads finish executing before printing this");
}
}
知道我做错了什么吗?或者有没有更好的方法来编写这些屏障同步方法?请帮忙。
最佳答案
在主线程执行期间,您创建了另外两个线程并告诉它们相互等待。但是你没有写任何东西让你的主线程等待它们并提示它不等待。尝试
CyclicBarrier barrier = new CyclicBarrier(3);
mythread thread1 = new mythread(barrier).start();
mythread thread2 = new mythread(barrier).start();
barrier.await(); // now you wait for two new threads to reach the barrier.
System.out.println("Should wait till both threads finish executing before printing this");
顺便说一句。除非必须,否则不要扩展 Thread 类。实现 Runnable 并将实现传递给 Thread 对象。像这样:
class MyRunnable implements Runnable {
public void run(){
// code to be done in thread
}
}
Thread thread1 = new Thread(MyRunnable);
thread1.start();
编辑
避免扩展 Thread 的理由。
经验法则是尽可能少的耦合。继承是类之间非常牢固的联系。如果你想改变它的一些默认行为(即覆盖一些方法)或者想访问类 Thread 的一些 protected 字段,你必须继承自 Thread。如果您不想要它,您可以选择更松散的耦合 - 实现 Runnable 并将其作为构造函数参数传递给 Thread 实例。
关于java - 如何让 java.concurrency.CyclicBarrier 按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522198/