两个线程循环打印ab10次

这个博客主要展示了如何使用Java实现线程交叉打印字符A和B。通过一个volatile变量flag作为同步标志,两个synchronized方法printA和printB确保线程交替打印,避免了竞态条件。程序中创建了多个线程,每个线程分别调用这两个方法,实现了AB交替打印的效果。
摘要由CSDN通过智能技术生成
package hy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;

public class Solution{
	// ab 线程交叉打印
	
	// 该变量可以理解成:上一次打印是否字符A
	private volatile boolean flag = false;
	public static void main(String[] args) {
		Solution so = new Solution();
		for(int i=0; i<10; i++){
			new Thread(so::printA).start();
			new Thread(so::printB).start();
		}
	}
	
	private synchronized void printA(){
		try{
			// 判断上一次打印是否 是打印的A,如果是就进行等待,如果不是就执行下面的代码
			while(flag){
				wait();
			}
			System.out.println("A");
			new Thread().sleep(500);
			flag = true;
			// 唤醒在等待的线程
			notifyAll();
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	
	private synchronized void printB(){
		try{
			// 判断上一次打印是否是打印B,如果是就进行等待,如果不是就执行下面的代码
			while(!flag){
				wait();
			}
			System.out.println("B");
			new Thread().sleep(500);
			flag = false;
			notifyAll();
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值