当前位置: 首页 > 工具软件 > Phaser > 使用案例 >

Phaser示例

别峻
2023-12-01
public class PhaserTest1 {
	
	private static final Random random = new Random(System.currentTimeMillis());

	public static void main(String[] args) {
		final Phaser phaser = new Phaser();
		IntStream.rangeClosed(1, 5).boxed().map(i->phaser).forEach(Task::new);
		phaser.register();
		phaser.arriveAndAwaitAdvance();
		System.out.println("All worker finished!!!");
	}
	
	static class Task extends Thread {
		
		private final Phaser phaser;
		
		Task(Phaser phaser) {
			this.phaser = phaser;
			this.phaser.register();
			start();
		}
		
		@Override
		public void run() {
			System.out.println("The worker ["+getName()+"] is working...");
			try {
				TimeUnit.SECONDS.sleep(random.nextInt(5));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			phaser.arriveAndAwaitAdvance();
		}
	}
}
public class PhaserTest2 {
	
	private static final Random random = new Random(System.currentTimeMillis());
	
	public static void main(String[] args) {
		final Phaser phaser = new Phaser(5);
		for(int i=1;i<6;i++) {
			new Sport(i, phaser).start();
		}
	}

	static class Sport extends Thread{
		
		private final int num;
		
		private final Phaser phaser;
		
		Sport(int num, Phaser phaser) {
			this.num = num;
			this.phaser = phaser;
		}
		
		@Override
		public void run() {
			try {
				System.out.println(num + "---start running!");
				TimeUnit.SECONDS.sleep(random.nextInt(5));
				System.out.println(num + "---end running!");
				System.out.println("getPhaser()==>" + phaser.getPhase());
				phaser.arriveAndAwaitAdvance();
				
				System.out.println(num + "---start basketball!");
				TimeUnit.SECONDS.sleep(random.nextInt(5));
				System.out.println(num + "---end basketball!");
				System.out.println("getPhaser()==>" + phaser.getPhase());
				phaser.arriveAndAwaitAdvance();
				
				System.out.println(num + "---start football!");
				TimeUnit.SECONDS.sleep(random.nextInt(5));
				System.out.println(num + "---end football!");
				System.out.println("getPhaser()==>" + phaser.getPhase());
				phaser.arriveAndAwaitAdvance();
			} catch (Exception e) {
				
			}
		}
	}
}

 

 类似资料: