Home > Mobile >  Java Thread Sync
Java Thread Sync

Time:12-31

I have a class Shop. In main i create 3 shop objects in main

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

@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. So every 30 days threads are waiting for each other.
It would be easiest to use Thread.join() but how can I use it when I'm in run().



I was also thinking about doing instead of 360 days, 12 times 30 days

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.

What can i do to synchronize this?

CodePudding user response:

You should get familiar with 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.

Note that you can optionally define a barrierAction, which is executed by last thread reaching the barrier.

See tutorial CyclicBarrier in Java

  • Related