Java多线程学习之:BlockingQueue实现生产者消费者

PCCommon:

public class PCCommon {
	private BlockingQueue<User> queue = new LinkedBlockingQueue<User>();
	//生产
	public void productData(User user){
		queue.add(user);
	}
	//消费
	public void consumerData(){
		User user = queue.poll();
		if(user != null){
			System.out.println("userid:"+user.getUserid());
			System.out.println("username:"+user.getUsername());
		}
	}
}

ConsumerThread:

public class ConsumerThread extends Thread{
	private PCCommon pcService;
	public ConsumerThread(PCCommon pcService){
		this.pcService=pcService;
	}
	@Override
	public void run(){
		while(true){
			pcService.consumerData();
		}
	}
}

PCTest:

public class PCTest {
	public static void main(String[] args){
		PCCommon pc = new PCCommon();
		ConsumerThread ct1 = new ConsumerThread(pc);
		ConsumerThread ct2 = new ConsumerThread(pc);
		ConsumerThread ct3 = new ConsumerThread(pc);
		ct1.start();
		ct2.start();
		ct3.start();
		User user1 = new User();
		user1.setUserid(1);
		user1.setUsername("username1");
		pc.productData(user1);
		
		User user2 = new User();
		user2.setUserid(2);
		user2.setUsername("username2");
		pc.productData(user2);
		
		User user3 = new User();
		user3.setUserid(3);
		user3.setUsername("username3");
		pc.productData(user3);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值