两个线程交替打印

本文介绍了如何实现两个线程按照A:1, B:1, A:2, B:2...的顺序交替打印数字。" 111720818,10297100,AIX系统与DS4700存储多路径聚合配置,"['AIX系统', '存储管理', '多路径技术', 'DS4700存储', '设备配置']
摘要由CSDN通过智能技术生成

两个线程交替打印

两个线程交替打印出 A:1 B:1 A:2 B:2 A:3 B:3

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource {
	private int num = 1;
	private Lock lock = new ReentrantLock();
	private Condition conditionA = lock.newCondition();
	private Condition conditionB = lock.newCondition();

	public void print3a(int r) {
		lock.lock();
		try {
			while (num != 1) {
				conditionA.await();
			}
			System.out.print(Thread.currentThread().getName() + r);
			System.out.print(" ");
			num = 2;
			conditionB.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void print3b(int r) {
		lock.lock();
		try {
			while (num != 2) {
				conditionB.await();
			}
			System.out.print(Thread.currentThread().getName() + r);
			System.out.print(" ");
			num = 1;
			conditionA.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}

public class Main {
	public static void main(String[] args) {
		ShareResource shareResource = new ShareResource();
		for (int i = 1; i < 4; i++) {
			int j = i;
			new Thread(() -> {
				shareResource.print3a(j);
			}, "A:").start();
			new Thread(() -> {
				shareResource.print3b(j);
			}, "B:").start();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值