多线程按序输出

本文探讨如何在Java中确保多线程环境下的顺序执行。通过使用原子类和阻塞队列两种方式,详细解释了如何设计程序,使得在三个不同线程A、B、C中,线程B的second()方法总是在线程A的first()方法之后执行,线程C的third()方法总是在线程B的second()方法之后执行。

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

我们提供了一个类: public class Foo { public void first() { print(“first”); }
public void second() { print(“second”); } public void third() {
print(“third”); } } 三个不同的线程 A、B、C 将会共用一个 Foo 实例。

一个将会调用 first() 方法 一个将会调用 second() 方法 还有一个将会调用 third() 方法 请设计修改程序,以确保
second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
力扣(LeetCode)

使用原子类实现
class Foo {
		private AtomicInteger atomicInteger = new AtomicInteger(0);
	    public Foo() { 
	    }
	    public void first(Runnable printFirst) throws InterruptedException {
	        // printFirst.run() outputs "first". Do not change or remove this line.
	        printFirst.run();
	        atomicInteger.incrementAndGet();
	    }

	    public void second(Runnable printSecond) throws InterruptedException {
	        // printSecond.run() outputs "second". Do not change or remove this line.
	    	while (atomicInteger.get() != 1) {
			}
	        printSecond.run();
	        atomicInteger.incrementAndGet();
	    }

	    public void third(Runnable printThird) throws InterruptedException {
	        // printThird.run() outputs "third". Do not change or remove this line.
	    	while (atomicInteger.get() != 2) {
			}
	    	printThird.run();
	        atomicInteger.incrementAndGet();
	    }
	}
使用阻塞队列
class Foo {
		
	    private BlockingQueue<Integer> oneBlockingQueue  = new LinkedBlockingQueue<Integer>();
		private BlockingQueue<Integer> twoBlockingQueue  = new LinkedBlockingQueue<Integer>();
		
	    public Foo() {
	        
	    }

	    public void first(Runnable printFirst) throws InterruptedException {
	        // printFirst.run() outputs "first". Do not change or remove this line.
	        printFirst.run();
	        oneBlockingQueue.put(1);
	    }

	    public void second(Runnable printSecond) throws InterruptedException {
	        // printSecond.run() outputs "second". Do not change or remove this line.
	        oneBlockingQueue.take();
	    	printSecond.run();
	        twoBlockingQueue.put(1);
	    }

	    public void third(Runnable printThird) throws InterruptedException {
	        // printThird.run() outputs "third". Do not change or remove this line.
	    	twoBlockingQueue.take();
	    	printThird.run();
	    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值