1. 程式人生 > >java多執行緒---順序列印ABC的三種實現---synchronized方式

java多執行緒---順序列印ABC的三種實現---synchronized方式

利用同步鎖,這種方式存在問題就是喚醒的過程中不能指定我說需要喚醒的執行緒,導致同一個鎖上的執行緒都喚醒了,因此條件判斷那裡使用了while迴圈

程式碼如下:

package com.zcj.thread;

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

public class PrintABC2 {
	 private int status =1;
	    public void printA(){
	    	synchronized(this){
	    		while(status!=1){
	    			try {
						this.wait();
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		}
	    		System.out.print("A");
	        	status=2;
	        	this.notifyAll();
	    	}
	    }
	    public void printB(){
	    	synchronized(this){
	    		while(status!=2){
	    			try {
						this.wait();
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		}
	    		System.out.print("B");
	        	status=3;
	        	this.notifyAll();
	    	}
	    }
	    public void printC(){
	    	synchronized(this){
	    		while(status!=3){
	    			try {
						this.wait();
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		}
	    		System.out.println("C");
	        	status=1;
	        	this.notifyAll();
	    	}
	    }
	    public static void main(String[] args){
	    	PrintABC2 print = new PrintABC2();
	    	Thread threadA = new Thread(new RunnableA2(print));
	    	Thread threadB = new Thread(new RunnableB2(print));
	    	Thread threadC = new Thread(new RunnableC2(print));
	    	threadA.start();
	    	threadB.start();
	    	threadC.start();
	    }
}

class RunnableA2 implements Runnable{
    private PrintABC2 print;
    
	public RunnableA2(PrintABC2 print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++){
			print.printA();
		}
	}
	
}
class RunnableB2 implements Runnable{
    private PrintABC2 print;
    
	public RunnableB2(PrintABC2 print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++){
			print.printB();
		}
		
	}
	
}
class RunnableC2 implements Runnable{
    private PrintABC2 print;
    
	public RunnableC2(PrintABC2 print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<10;i++){
			print.printC();
		}
	}
	
}