Java线程同步

Java Thread Sync

我有一个 class 商店。在 main 中,我在 main

中创建了 3 个商店对象
Thread thread1 = new Thread(shop1);
Thread thread2 = new Thread(shop2);
Thread thread3 = new Thread(shop3);


threads.add(thread1);
threads.add(thread2);
threads.add(thread3);

for (Thread t : threads) {
    t.start();
}

运行店内方法class

@Override
public void run() {

   for(int day=0;day<=360;++day) {
      if (day% 30 == 0) {
         delivery();
     }

CODE...
   }
}

我希望线程每 30 天同步一次。所以每 30 天线程就会互相等待。
使用 Thread.join() 最简单,但是当我在 运行() 时如何使用它。



我也在考虑做而不是360天,12次30天

public void run() {

   for(int day=0;day<30;++day) {
      if (day% 30 == 0) {
         delivery();
     }

CODE...

并在 main join() 中使用,但如何重新启动该方法时出现问题。

我该怎么做才能同步它?

您应该熟悉 CyclicBarrier class。

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

请注意,您可以选择定义一个 barrierAction,它由到达屏障的最后一个线程执行。

查看教程CyclicBarrier in Java