36

用阻塞队列,再系一次鞋带

 3 years ago
source link: https://mp.weixin.qq.com/s/Bn8kUPPeNrvGfpBYbUJHjw
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

用阻塞队列,再系一次鞋带

原创 dafei1288 麒思妙想 1周前
640?wx_fmt=jpeg

题干,是这样的,通过2个线程,交替输出 A1B2C3....Z26

dafei1288,公众号:麒思妙想如何让两个线程“系鞋带"

在上篇文章里,通过锁打印资源实现了需求,但是总觉着这个代码不够优雅,然后搞了一个阻塞队列的方式,至少代码上,感觉优雅了很多。

import java.util.concurrent.LinkedTransferQueue;
public class TwoThreadQueue {
public static final int SETPS = 26;
public static void main(String[] args) {
LinkedTransferQueue<String> tq = new LinkedTransferQueue<>();
new Thread(()->{
int startCharCount = 65;
for (int i = 0; i < SETPS; i++) {
try {
tq.transfer((char) startCharCount+++"");
System.out.println(Thread.currentThread().getName() + " " +tq.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"str").start();
new Thread(()->{
int startCharCount = 1;
for (int i = 0; i < SETPS; i++) {
try {
System.out.println(Thread.currentThread().getName() + " " +tq.take());
tq.transfer(startCharCount+++"");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"num").start();
System.out.println(tq.size());
}
}

大体的执行流程,如下图所示,字符串线程将A交给队列,然后进入阻塞状态,数字线程获取内容并进行打印,然后将1交给队列,再进入阻塞状态,字符串线程被叫起,拿走1打印,再将B交给队列,以此类推。

640?wx_fmt=png

LinkedTransferQueue 的类图如下

640?wx_fmt=png

LinkedTransferQueue 该类实现了一个 TransferQueue。该接口定义了几个方法:

public interface TransferQueue<E> extends BlockingQueue<E> {
// 如果可能,立即将元素转移给等待的消费者。
// 更确切地说,如果存在消费者已经等待接收它(在 take 或 timed poll(long,TimeUnit)poll)中,则立即传送指定的元素,否则返回 false。
boolean tryTransfer(E e);
// 将元素转移给消费者,如果需要的话等待。
// 更准确地说,如果存在一个消费者已经等待接收它(在 take 或timed poll(long,TimeUnit)poll)中,则立即传送指定的元素,否则等待直到元素由消费者接收。
void transfer(E e) throws InterruptedException;
// 上面方法的基础上设置超时时间
boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException;
// 如果至少有一位消费者在等待,则返回 true
boolean hasWaitingConsumer();
// 返回等待消费者人数的估计值
int getWaitingConsumerCount();
}

参考链接:https://www.cnblogs.com/stateis0/p/9062076.html

历史文章导读

如果文章对您有那么一点点帮助,我将倍感荣幸

欢迎  关注、在看、点赞、转发 

640?wx_fmt=jpeg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK