四个线程分别依次打印A/B/C/D,每个线程打印一个字母

这是一个Java程序,通过多线程实现四个线程PrintA、PrintB、PrintC和PrintD依次打印字母A、B、C和D。程序使用枚举类型PrintStatus跟踪当前应打印的字符,并利用synchronized关键字保证打印的顺序。每个线程在一个无限循环中调用print方法尝试打印其对应的字符,并在打印完D后换行。
摘要由CSDN通过智能技术生成
/**
 * 四个线程ABCD,分别打印A/B/C/D
 */
public class ABCD {
	public static void main(String[] args) {
		new PrintABCD().start();
	}
}

class PrintABCD {
	private static enum PrintStatus {
		A, B, C, D
	};

	private static PrintStatus nstatus;

	public void start() {
		nstatus = PrintStatus.A;

		Thread thread1 = new Thread(new PrintA());
		Thread thread2 = new Thread(new PrintB());
		Thread thread3 = new Thread(new PrintC());
		Thread thread4 = new Thread(new PrintD());

		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
	}

	private synchronized void print(PrintStatus status) {
		if (nstatus == status) {
			// System.out.println(Thread.currentThread().getName() + " ");
			System.out.print(status);
			if (status == PrintStatus.D) {
				System.out.println();
			}
			changeStatus();
			return;
		}

	}

	private void chan
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值