编写一个程序,启动三个线程,三个线程的ID分别是A,B,C; 每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC...

这篇博客介绍如何在Java中编写一个程序,启动三个线程,它们的ID分别为A、B、C。每个线程按特定顺序(ABCABC...)在屏幕上打印自己的ID五次,利用`synchronized`关键字、`wait()`和`notify()`来实现线程间的同步与通信。

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

public class Test {

// flag为0就打印A,为1就打印B,为2就打印C
// 利用多线程的synchronized关键字,主要使用wait和notify
private int flag = 0;

public synchronized void printA() {
	try {
		for (int i = 1; i <= 5; i++) {
			while (flag != 0) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName());
			flag = 1;
			this.notifyAll();
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

public synchronized void printB() {
	try {
		for (int i = 1; i <= 5; i++) {
			while (flag != 1) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName());
			flag = 2;
			this.notifyAll();
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	}

}

public synchronized void printC() {
	try {
		for (int i = 1; i <= 5; i++) {
			while (flag != 2) {
				this.wait();
			}
			System.out.println(Thread.currentThread().getName());
			flag = 0;
			this.notifyAll(); 
		}
	} catch (InterruptedException e) {
		e.printStackTrace
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值