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();
}
}
練習:利用多線程 按照順序將 ABC 打印十遍 ,體會 lock 和 condition 的用法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.