java多线程---顺序打印ABC的三种实现---synchronized方式

本文探讨了使用Java同步锁来顺序打印ABC的三种实现方法,重点在于解决在唤醒线程时可能存在的问题。通过示例代码展示了如何利用while循环进行条件判断,确保线程按预期顺序执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用同步锁,这种方式存在问题就是唤醒的过程中不能指定我说需要唤醒的线程,导致同一个锁上的线程都唤醒了,因此条件判断那里使用了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();
		}
	}
	
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值