ITeye博客

线程池问题

GLC · 2014-04-11 12:05 · java基础 · 线程池 · 移动开发 · Markdown

这道题花了我比较长的时间、总体来讲,现在做出来后、感觉还好。

两条流水线、三个工人,不用想,就是实例化两个生产线程及三个取货线程

首先我们不急着写线程。 先写产品对象:


/**
	 * 生产类
	 */
	static class Producter{
		
		private int number;//产品编号
		
		public void product(){
			
			count++;
			this.setNumber(count);
			System.out.println("进行生产第"+count+"件产品");
		}
		
		public int getNumber() {
			return number;
		}
		public void setNumber(int number) {
			this.number = number;
		}
	}


对了、我们得定义一个全局变量:记录第多少号产品 private static int count=0;//第几件产品

然后、我们可以写流水线了


/**
	 * 生产线
	 */
	static class ProductThread extends Thread{
		private Queue<Producter> queue;
		
		public ProductThread(Queue<Producter> queue){
			this.queue = queue;
		}
		public void run(){
			while(queue.size()<6){
				
				
					Producter producter = new Producter();
					producter.product();
					queue.add(producter);
					try{
						Thread.sleep(1000);
					}catch(InterruptedException e){
						return;
					}
				}
				
				
				
			}
		}


然后再写工人类


/**
	 * 工人类
	 */
	static class CustomerThread extends Thread{
		private Queue<Producter> queue1;
		private Queue<Producter> queue2;
		private Producter produection;
		public CustomerThread(Queue<Producter> queue1,Queue<Producter> queue2){
			this.queue1 = queue1;
			this.queue2 = queue2;
		}
		
		public void run(){
			while(queue1.size()>0||queue2.size()>0){
				
					//判断应该从哪条线上取
					if(queue1.size()>queue2.size()){
						produection = (Producter)queue1.remove();
					}else{
						produection = (Producter)queue2.remove();
					}
					System.out.println("取下产品第"+produection.getNumber()+"件产品");
					try{
						Thread.sleep(1000);
					}catch(InterruptedException e){
						return;
					}
				}
			
		}


最后主函数中进行生产



/**
	 * 主函数
	 * @param args
	 */
	public static void main(String[] args){
		System.out.println("=============================");
		//存放生产线上的产品数
		Queue<Producter> queue1 = new  ArrayDeque<Producter>();
		Queue<Producter> queue2 = new  ArrayDeque<Producter>();
		
		ProductThread thread1 = new ProductThread(queue1);
		ProductThread thread2 = new ProductThread(queue2);
		thread1.start();
		thread2.start();
		System.out.println("---------------------");
		//三个工人开始取产品
		CustomerThread coustomer1 = new CustomerThread(queue1,queue2);
		coustomer1.start();
		CustomerThread coustomer2 = new CustomerThread(queue1,queue2);
		coustomer2.start();
		CustomerThread coustomer3 = new CustomerThread(queue1,queue2);
		coustomer3.start();
		
		
	}

这样做了之后、我运行发现有问题;生产时、会产生相同编号的产品。 通过查找资料发现,这是因为在生产过程中、没有加同步锁; 现在我们只需要对工人拿产品 及生产线生产产品的地方加同步锁;就解决了这个问题

都是加在while()的条件下synchronized(this){}

最后、源码附上;欢迎大家批评指正

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。