CyclicBarrier를 이용하는 방법.
public class SynchronizedThread extends Thread {
private CyclicBarrier entryBarrier; private CyclicBarrier exitBarrier;
public SynchronizedThread(Runnable runnable, CyclicBarrier entryBarrier, CyclicBarrier exitBarrier) {
super(runnable); this.entryBarrier = entryBarrier; this.exitBarrier = exitBarrier;
}
@Override public void run() {
try {
entryBarrier.await(); super.run(); exitBarrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class SynchronizedThreadTest {
@Test public void testMultithread() throws InterruptedException, BrokenBarrierException {
Runnable r = new Runnable() {
public void run() {
System.out.println("thread=" + Thread.currentThread().getId() + ", started !!!"); long millis = 3 * 1000l; try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("thread=" + Thread.currentThread().getId() + ", done !!!");
}
};
int numberOfThreads = 10;
System.out.println("before start");
CyclicBarrier entryBarrier = new CyclicBarrier(numberOfThreads + 1); CyclicBarrier exitBarrier = new CyclicBarrier(numberOfThreads + 1);
for (int i = 0; i < numberOfThreads; i++) {
// new Thread(r).start(); new SynchronizedThread(r, entryBarrier, exitBarrier).start();
}
System.out.println("after start");
System.out.println("before entryBarrier.await();"); entryBarrier.await();
System.out.println("before exitBarrier.await();"); exitBarrier.await();
System.out.println("after exitBarrier.await();");
}
}