题干,是这样的,通过2个线程,交替输出 A1B2C3....Z26dafei1288
在上篇文章里,通过锁打印资源实现了需求,但是总觉着这个代码不够优雅,然后搞了一个阻塞队列的方式,至少代码上,感觉优雅了很多。
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交给队列,以此类推。
LinkedTransferQueue 的类图如下
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
本文分享自微信公众号 - 麒思妙想(qicai1612),作者:dafei1288
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2020-08-10
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句