日期:2014-05-20 浏览次数:21070 次
public class TestDemo {
	public static void main(String[] args) {
		final Locker p = new Locker();
		Task11 a = new Task11(p);
		Task21 b = new Task21(p);
		Task31 c = new Task31(p);
		Thread one = new Thread(a);
		one.start();
		Thread two = new Thread(b);
		two.start();
		Thread three = new Thread(c);
		three.start();
	}
}
class Task11 implements Runnable {
	
	private Locker obj;
	public Task11(Locker p){
		this.obj = p;
	}
	
	@Override
	public void run() {
		for(int i = 0; i < 5; i++){
			synchronized (obj) {
				if(obj.num != 0){
					try {
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}else{
					System.out.println("a");
					obj.num = 1;
					obj.notifyAll();
				}
			}
		}
	}
}
class Task21 implements Runnable {
	
	private Locker obj;
	public Task21(Locker p){
		this.obj = p;
	}
	
	@Override
	public void run() {
		for(int i = 0; i < 5; i++){
			synchronized (obj) {
				if(obj.num != 1){
					try {
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}else{
					System.out.println("b");
					obj.num = 2;
					obj.notifyAll();
				}
			}
		}
	}
}
class Task31 implements Runnable {
	
	private Locker obj;
	public Task31(Locker p){
		this.obj = p;
	}
	
	@Override
	public void run() {
		for(int i = 0; i < 5; i++){
			synchronized (obj) {
				if(obj.num != 2){
					try {
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}else{
					System.out.println("c");
					obj.num = 0;
					obj.notifyAll();
				}
			}
		}
	}
}
class Locker {
	int num = 0;
}
public class TestDemo {
public static void main(String[] args) {
final Locker p = new Locker();
Task11 a = new Task11(p);
Task21 b = new Task21(p);
Task31 c = new Task31(p);
Thread one = new Thread(a);
one.start();
Thread two = new Thread(b);
two.start();
// Thread three = new Thread(c);
// three.start();
}
}
class Task11 implements Runnable {
private Locker obj;
public Task11(Locker p){
this.obj = p;
}
@Override
public void run() {
for(int i = 0; i < 5; i++){
synchronized (obj) {
if(obj.num != 0){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("a");
obj.num = 1;