Source Code : Using the reusable synchronization barrier Phaser
Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com.
Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com.
Click Here or search from google with Libraries Name you get jar file related it
Using the reusable synchronization barrier Phaser
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicInteger;
abstract class Entity implements Runnable {
public abstract void run();
}
class WorkerA extends Entity implements Runnable {
AtomicInteger idSource = new AtomicInteger();
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Override
public String toString() {
int id = idSource.incrementAndGet();
return "# " + id;
}
}
class WorkB extends Entity implements Runnable {
AtomicInteger idSource = new AtomicInteger();
public void run() {
try {
Thread.sleep(400);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Override
public String toString() {
int id = idSource.incrementAndGet();
return "ID:" + id;
}
}
public class Test {
private static void gameEngine(List<Entity> entities) {
final Phaser phaser = new Phaser(1);
for (final Entity entity : entities) {
final String member = entity.toString();
System.out.println(member);
phaser.register();
new Thread() {
@Override
public void run() {
System.out.println(member);
phaser.arriveAndAwaitAdvance();
entity.run();
}
}.start();
}
phaser.arriveAndDeregister();
}
public static void main(String[] args) {
List<Entity> entities = new ArrayList<>();
entities = new ArrayList<>();
entities.add(new WorkerA());
entities.add(new WorkB());
gameEngine(entities);
}
}
Thank with us