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();
		}
	}
	
}


你可能感兴趣的:(Java)