import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank">sincronizzazione di un thread pool, per raggiungere un punto comune di
 * una barriera</a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {
	private static class WorkerThread implements Runnable {
		private CyclicBarrier cyclicBarrier;
		private int bufProcess;
		private List<List<Integer>> bufPartialProcess;

		public WorkerThread(CyclicBarrier cyclicBarrier, int bufProcess,
				List<List<Integer>> bufPartialProcess) {
			super();
			
			this.cyclicBarrier = cyclicBarrier;
			this.bufProcess = bufProcess;
			this.bufPartialProcess = bufPartialProcess;
		}

		/**
		 * @see CyclicBarrier#await()
		 * 
		 */
		@Override
		public void run() {
			Random random = new Random();
			String thread = Thread.currentThread().getName();

			// processo parziale
			List<Integer> buf = new ArrayList<>();
			for (int i = 0; i < bufProcess; i++) {
				Integer num = random.nextInt(10);
				buf.add(num);
			}

			bufPartialProcess.add(buf);

			try {
				System.out.println(thread + " è in attesa alla barriera ");
				cyclicBarrier.await();
			} catch (InterruptedException e) {
			} catch (BrokenBarrierException e) {
			}
		}
	}
	
	private static class AggregatorThread implements Runnable {
		private List<List<Integer>> bufPartialProcess;
			
		public AggregatorThread(List<List<Integer>> bufPartialProcess) {
			super();
			this.bufPartialProcess = bufPartialProcess;
		}

		@Override
		public void run() {
			// collettore
			int collect = 0;
			for (List<Integer> partialProcess : bufPartialProcess) {
				for (Integer process : partialProcess) {
					System.out.print(process + " ");
					collect += process;
				}
				System.out.println();
			}

			System.out.println("Thread barriera in elaborazione = " + collect);
		}
	}

	private static class UniTest {

		/**
		 * @see CyclicBarrier#CyclicBarrier(int, Runnable)
		 * @see CyclicBarrier#reset()
		 * 
		 */
		public void simulate(int workers) {			
			 List<List<Integer>> bufPartialProcess = Collections.synchronizedList(new ArrayList<>());
			 CyclicBarrier cyclicBarrier = new CyclicBarrier(workers, new AggregatorThread(bufPartialProcess));
			for (int i = 0; i < workers; i++) {
				Thread worker = new Thread(new WorkerThread(cyclicBarrier, 3, bufPartialProcess));

				worker.setName("Thread " + i);
				worker.start();
			}
			 
			while( cyclicBarrier.getNumberWaiting() != 0)
				;
			
			cyclicBarrier.reset();
		}
	}

	public static void main(String args[]) {
		// Unit test - check-poin in un thred pool
		new UniTest().simulate(5);	
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: