Thinking in Java学习笔记

LinkedBlockingQueue

ArrayBlockingQueue

SynchronizedBlockingQueue

TestBlockingQueue.java


package com.test.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestBlockingQueue {
	static void getKey(){
		try {
			(new BufferedReader(new InputStreamReader(System.in))).readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	static void getKey(String msg){
		System.out.println(msg);
		getKey();
	}
	static void test(String msg, BlockingQueue<LiftOff> queue){
		System.out.print(msg);
		LiftOffRunner runner=new LiftOffRunner(queue);
		Thread t=new Thread(runner);
		t.start();
		
		for(int i=0;i<5;i++){
			runner.add(new LiftOff(5));
		}
		getKey("Press 'Enter'("+msg+")");
		t.interrupt();
		System.out.println("finished "+msg+" test");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		test("LinkedBlockingQueue",new LinkedBlockingQueue<LiftOff>());
		test("ArrayBlockingQueue",new ArrayBlockingQueue<LiftOff>(3));
		test("SynchronousQueue",new SynchronousQueue<LiftOff>());
	}

}
class LiftOffRunner implements Runnable{
	private BlockingQueue<LiftOff> rockets;
	public LiftOffRunner(BlockingQueue<LiftOff> queue){
		this.rockets=queue;
	}
	public void add(LiftOff lo){
		try{
			rockets.put(lo);
		}catch(InterruptedException e){
			System.out.println("interrupted during put()");
		}
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		while(!Thread.interrupted()){
			LiftOff rocket;
			try {
				rocket = rockets.take();
				rocket.run();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("LiftOff Runner Exiting!!");
	}
	
}
class LiftOff implements Runnable {
	static int taskCount=0;
	private final int id=taskCount++;
	protected int countDown=10;
	public LiftOff(){}
	public LiftOff(int countDown){
		this.countDown=countDown;
	}
	public String status(){
		return "#"+id+"("+(countDown==0?"LiftOff":countDown)+"), ";
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(countDown-->0){
			System.out.print(status());
			Thread.yield();
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值