循环打印ABC

package com.pp.test02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MainClass {
	
	public static void main(String[] args) {
		MyCoo coo = new MyCoo();
		A a = new A(coo);
		B b = new B(coo);
		C c = new C(coo);
		
		Thread t0 = new Thread(a);
		Thread t1 = new Thread(b);
		Thread t2 = new Thread(c);
		
		t0.start();
		t1.start();
		t2.start();
	}
	
}

class MyCoo{
	String flag = "a";
	public ReentrantLock lock = new ReentrantLock();
	public Condition con_a = lock.newCondition();
	public Condition con_b = lock.newCondition();
	public Condition con_c = lock.newCondition();
}
package com.pp.test02;

public class A implements Runnable{
	private MyCoo coo ;
	

	public A(MyCoo coo) {
		super();
		this.coo = coo;
	}


	@Override
	public void run() {
		while(true) {
			coo.lock.lock();
			if(coo.flag.equals("a")) {
				System.out.println("A");
				try {
					Thread.sleep(1000);
					coo.flag="b";
					coo.con_b.signal();
					coo.con_a.await();
		
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}			
			coo.lock.unlock();
		}
		
	}

}
package com.pp.test02;

public class B implements Runnable{
	private MyCoo coo ;
	

	public B(MyCoo coo) {
		super();
		this.coo = coo;
	}


	@Override
	public void run() {
		while(true) {
			coo.lock.lock();
			if(coo.flag.equals("b")) {
				System.out.println("B");
				try {
					
					Thread.sleep(1000);
					coo.flag="c";
					coo.con_c.signal();
					coo.con_b.await();

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}			
			coo.lock.unlock();
		}
		
	}

}
package com.pp.test02;

public class C implements Runnable{

	private MyCoo coo ;
	

	public C(MyCoo coo) {
		super();
		this.coo = coo;
	}


	@Override
	public void run() {
		while(true) {
			coo.lock.lock();
			if(coo.flag.equals("c")) {
				System.out.println("C");
				try {
					Thread.sleep(1000);
					coo.flag="a";
					coo.con_a.signal();
					coo.con_c.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}			
			coo.lock.unlock();
		}
		
	}
}

 

你可能感兴趣的:(循环打印ABC)