论坛首页 招聘求职论坛

java-同步访问一个数组Integer[10],生产者不断地往数组放入整数1000,数组满时等待;消费者不断地将数组里面的数置零,数组空时等待

浏览 3019 次
精华帖 (0) :: 良好帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-04-14   最后修改:2012-04-14
这样做对不对?
多线程编程是我的短板。请大家指教

public class PC {

	/**
	 * 题目:生产者-消费者。
	 * 同步访问一个数组Integer[10],生产者不断地往数组放入整数1000,数组满时等待;消费者不断地将数组里面的数置零,数组空时等待。
	 */
	
	private static final Integer[] val=new Integer[10];
	private static int size=0;
	private static final int MAX_SIZE=10;
	
	public static void main(String[] args)  {
		PC pc=new PC();
		new Thread(pc.new P()).start();
		new Thread(pc.new C()).start();
	}

	public synchronized void consume(){
			while(size<=0){
				try {
					System.out.println(size+"- consume wait");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			val[--size]=0;
			notifyAll();
			System.out.println("successful consume and now size="+size);
	}
	
	public  synchronized void produce(int value){ 
			while(size==MAX_SIZE){
				try {
					System.out.println(size+"- produce wait");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			val[size++]=value;
			notifyAll();
			System.out.println("successful produce and now size="+size);
	}
	
	class P implements Runnable{
		public void run(){
			while(true)produce(1000);
		}
	}
	
	class C implements Runnable{
		public void run(){
			while(true)consume();
		}
	}
	
}

   发表时间:2012-04-15  
等待是要在条件上等待,而不是在数据上等待,用JAVA并发包
0 请登录后投票
   发表时间:2012-04-15  
生产者消费者的基本问题将队列改成了数组

PS:你这是迅雷社招java笔试题的最后一题吧,当时去拿到了心里期望了几年的迅雷的offer,职位是我梦寐以求的云计算后台开发,无奈当时另外的诱惑让我选择与迅雷失之交臂,目前还对其充满向往
0 请登录后投票
论坛首页 招聘求职版

跳转论坛:
Global site tag (gtag.js) - Google Analytics