阻塞队列 BlockingQueue LinkedBlockingQueue

package com.ctl.util.ThreadPool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/*阻塞队列* */
public class Demo04 {
	Thread tom;// tom receive
	Thread jerry;// jerry send
	BlockingQueue<String> queue;

	class Tom extends Thread {
		public void run() {
			while (true) {
					try {
						String msg=queue.poll(1, TimeUnit.SECONDS);
						if(msg==null){continue;}
						System.out.println("Tom receive:   "+msg);
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						System.err.println("InterruptedException"+e);
					}
			}
		}
	}

	class Jerry extends Thread {
		int i = 0;

		public void run() {
			while (true) {
				String hello = "HI!" + i;
				try {
					// 如果等待5秒插入失败返回false成功返回true
					boolean success = queue.offer(hello, 2, TimeUnit.SECONDS);
					// 如果插入成功 i++ 否则继续插入
					if (success) {
						System.out.println("添加信息成功\t"+hello);
						i++;
					} else {
						System.out.println("满了,重试");
						continue;
					}
				} catch (InterruptedException e) {
					System.err.println("InterruptedException" + e);
				}
			}
		}
	}

	public void start() {
		queue = new LinkedBlockingQueue<String>(3);// 超过3个就满了
		tom = new Tom();
		jerry = new Jerry();
		tom.start();
		jerry.start();
	}

	public static void main(String[] args) {
		new Demo04().start();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值