练习:利用多线程 按照顺序将 ABC 打印十遍 ,体会 lock 和 condition 的用法

import java.util.concurrent.locks.*;

class Print
{
	private int flag = 1;
	private int count = 0;
	private Lock lock = new ReentrantLock();
	private Condition condition_A = lock.newCondition();
	private Condition condition_B = lock.newCondition();
	private Condition condition_C = lock.newCondition();
	public int getCount()
	{
		return count;
	}
	public int getCountPlus()
	{
		return count++;
	}
	public void printA() throws InterruptedException
	{
		lock.lock();
		try
		{
			while(flag!=1)
				condition_A.await();
			
			System.out.print("A");
			flag = 2;
			condition_B.signal();
		}
		finally
		{
			lock.unlock();
		}
	}

	public void printB() throws InterruptedException
	{
		lock.lock();
		try
		{
			while(flag!=2)
				condition_B.await();
				
			System.out.print("B");
			flag = 3;
			condition_C.signal();		
		}
		finally
		{
			lock.unlock();
		}
	}

	public void printC() throws InterruptedException
	{
		lock.lock();
		try
		{
			while(flag!=3)
				condition_C.await();
				
			System.out.println("C");
			flag = 1;
			condition_A.signal();	
		}
		finally
		{
			lock.unlock();
		}
	}
}

class PrintA implements Runnable
{
	private Print p1;
	PrintA(Print p1)
	{
		this.p1 = p1;
	}
	public void run()
	{
		while (p1.getCount() < 10)
		{
			try
			{
				p1.printA();
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}

class PrintB implements Runnable
{
	private Print p2;
	PrintB(Print p2)
	{
		this.p2 = p2;
	}
	public void run()
	{
		while (p2.getCount() <10)
		{
			try
			{
				p2.printB();
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}
class PrintC implements Runnable
{
	private Print p3;
	PrintC(Print p3)
	{
		this.p3 = p3;
	}
	public void run()
	{
		while (p3.getCountPlus() < 10)
		{
			try
			{
				p3.printC();
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}
class LockTest 
{
	public static void main(String[] args) 
	{
		int count = 0;
		Print p = new Print();
		new Thread(new PrintA(p)).start();
		new Thread(new PrintB(p)).start();
		new Thread(new PrintC(p)).start();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值