好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:CyclicBarrier

最近在整理 Java 的多线程相关的技术,这里备份下关于【 CyclicBarrier 】代码。CyclicBarrier主要是用来在各个线程间进行等待的工具。

github:

https://github.com/cstriker1407/think_in_java 】

CyclicBarrierTest.java类:

public class CyclicBarrierTest
{
	public static void test()
	{
		final CyclicBarrier barrer = new CyclicBarrier(3, new Runnable()
		{
			@Override
			public void run()
			{
				System.out.println("The players have arrived pos");
			}
		});
		new Player(barrer, "player1").start();
		new Player(barrer, "player2").start();
		new Player(barrer, "player3").start();
	}

}
class Player extends Thread
{
	public Player(CyclicBarrier barrer, String name)
	{
		super();
		this.barrer = barrer;
		this.name = name;
	}
	private CyclicBarrier barrer;
	private String name;
	@Override
	public void run()
	{
		try
		{
			Thread.sleep(new Random().nextInt(5));
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		
		try
		{
			System.out.println("player:"+ name + " is Arriving Pos1");
			barrer.await();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("player:"+ name + " is go on");
		
		try
		{
			Thread.sleep(new Random().nextInt(5));
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		
		try
		{
			System.out.println("player:"+ name + " is Arriving Pos2");
			barrer.await();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("player:"+ name + " is finish");
	}
}

 日志打印:

player:player2 is Arriving Pos1
player:player1 is Arriving Pos1
player:player3 is Arriving Pos1
The players have arrived pos
player:player3 is go on
player:player2 is go on
player:player1 is go on
player:player2 is Arriving Pos2
player:player1 is Arriving Pos2
player:player3 is Arriving Pos2
The players have arrived pos
player:player3 is finish
player:player2 is finish
player:player1 is finish

 备注:

通过日志可以发现,当多个线程的执行进度不一样时,可以利用CyclicBarrier进行统一进度。

Leave a Reply

6 − 3 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据