简体   繁体   English

Java 线程同步

[英]Java Thread Sync

I have a class Shop.我有一个 class 商店。 In main i create 3 shop objects in main在 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();
}

run method in the shop class店内运行方法 class

@Override
public void run() {

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

CODE...
   }
}

I would like threads to sync every 30 days.我希望线程每 30 天同步一次。 So every 30 days threads are waiting for each other.所以每 30 天线程都在等待对方。
It would be easiest to use Thread.join() but how can I use it when I'm in run().使用 Thread.join() 是最简单的,但是当我在 run() 中时如何使用它。



I was also thinking about doing instead of 360 days, 12 times 30 days我也在考虑做而不是360天,12次30天

public void run() {

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

CODE...

and use in main join() but then there is a problem how to restart the method.并在 main join() 中使用,但是如何重新启动该方法存在问题。

What can i do to synchronize this?我该怎么做才能同步呢?

You should get familiar with CyclicBarrier class.您应该熟悉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. CyclicBarriers 在涉及固定大小的线程组的程序中很有用,这些线程组必须偶尔相互等待。 The barrier is called cyclic because it can be re-used after the waiting threads are released.屏障被称为循环的,因为它可以在等待线程被释放后重新使用。

Note that you can optionally define a barrierAction, which is executed by last thread reaching the barrier.请注意,您可以选择定义一个barrierAction,它由到达屏障的最后一个线程执行。

See tutorial CyclicBarrier in Java请参阅Java 中的教程 CyclicBarrier

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM