`

wait() 和notify重温

 
阅读更多
重温wait()和notify()


    温故知新,接下来看看线程池。
   
    同时启动3个线程A、B、C,A线程输出A 20次,B线程输出B 20次,C线程输出C 20次,要求输出结果为顺序输出A、B、C、A、B、C。。。



class Agent{
	public static int state = 1;

	public synchronized void sayA() {
		if(state != 1){
			try {
				super.wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println("A");
		state = 2;
		super.notify();
	}
	public synchronized void sayB() {
		if(state != 2){
			try {
				super.wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println("B");
		state = 3;
		super.notify();
	}
	public synchronized void sayC() {
		if(state != 3){
			try {
				super.wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println("C");
		state = 1;
		super.notify();
	}
}

class A extends Thread{
	Agent agent;
	public A(Agent agent){
		this.agent = agent;
	}
	public void run(){
		for(int i=0;i<20;i++){
			try {
				Thread.sleep(200);
			} catch (Exception e) {
			}
			agent.sayA();
		}
	}
}
class B extends Thread{
	Agent agent;
	public B(Agent agent){
		this.agent = agent;
	}
	public void run(){
		for(int i=0;i<20;i++){
			try {
				Thread.sleep(200);
			} catch (Exception e) {
			}
			agent.sayB();
		}
	}
}
class C extends Thread{
	Agent agent;
	public C(Agent agent){
		this.agent = agent;
	}
	public void run(){
		for(int i=0;i<20;i++){
			try {
				Thread.sleep(200);
			} catch (Exception e) {
			}
			agent.sayC();
		}
	}
}

public class TestWait {
	public static void main(String[] args) {
		Agent agent = new Agent();
		new A(agent).start();
		new B(agent).start();
		new C(agent).start();
	}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics