首页 > 试题广场 >

用Java代码模拟实现:一个人不断往箱子里放苹果,另一个人不

[问答题]
用Java代码模拟实现:一个人不断往箱子里放苹果,另一个人不断从箱子里取苹果,箱子只能放5个苹果,苹果数量无限。要求不使用java.util.concurrent包中的类。
static List<String> list = Collections.synchronizedList(new ArrayList<String>());
    int size = 5;
    static int apple  = 0;
    public static void main(String[] args) throws InterruptedException {
        InputApple inputApple = new InputApple();
        OutputApple outputApple = new OutputApple();
        new Thread(inputApple).start();
        new Thread(outputApple).start();
    }
    /**
     * 放入
     * */
    private static class InputApple implements Runnable{
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(new Random().nextInt(3)*900);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(list.size() < 5){
                    apple ++;
                    list.add(""+apple);
                    System.out.println("放入");
                }else{
                    System.out.println("已经放满");
                }
            }
        }
    }
    /**
     * 拿出
     * */
    private static class OutputApple implements Runnable{
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(new Random().nextInt(3)*800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(list.size() > 0){
                    list.remove(new Random().nextInt(list.size()));
                    System.out.println("拿走");
                }else{
                    System.out.println("已经空了");
                }
            }
        }
        
    }
发表于 2015-06-10 16:56:16 回复(4)
//多生产多消费,生产多个苹果放在容器中,但是该容器只能存放5个苹果
//公共资源类
import java.util.LinkedList;
class Box
{	
	private final int MAX_SIZE=5;//仓储最大容量
	private LinkedList <Object> list = new LinkedList<Object>();//仓储容器
	//增加公共资源
	public void increase(){
		synchronized(list){
			while(list.size() > MAX_SIZE){
				System.out.println("...现在箱子中苹果的数量:"+list.size()+
					"箱子中的苹果超过5个,暂时不能执行任务!");
				try{list.wait();}catch(InterruptedException e ){e.printStackTrace();}
			}
			list.add(new Object());
			System.out.println("...往箱子中放入1个苹果,现在箱子中苹果的数量:"+list.size());
			list.notifyAll();
			}	
	}
	//减少公共资源
	public void decrease(){
		synchronized(list){
			while(list.size()<1){
				System.out.println("现在箱子中苹果的数量:"+list.size()+
					"箱子中苹果数量不足1个,暂时不能执行生产任务!");
				try{list.wait();} catch(InterruptedException e ){e.printStackTrace();}
			}
			list.remove();//从集合中移除
			System.out.println("从箱子中取出1个苹果,现在箱子中苹果的数量:"+list.size());
			list.notifyAll();
			}
		}		
	}

//生产者
class Producer implements Runnable
{
	private Box box;
	Producer(Box box){
		this.box = box;
	}
	public void run(){
		while(true){
			try
			{
				Thread.sleep((long)(Math.random()*1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			box.increase();
		}
	}
}
//消费者
class Consumer implements Runnable
{
	private Box box;
	public Consumer(Box box){
		this.box = box;
	}
	public void run(){
		 while(true){
			try
			{
				Thread.sleep((long)(Math.random()*1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			box.decrease();
		 }
	}
}
class BoxAppleThread 
{
	public static void main(String[] args) 
	{
		//创建资源对象
		Box box = new Box();
		//创建线程任务对象
		Producer pro = new Producer(box);
		Consumer con = new Consumer(box);
		//创建线程
		new Thread(pro).start();
		new Thread(con).start();
		new Thread(pro).start();
		new Thread(con).start();
	}
}
--------------------------------------------------------------------------------------------------------------------------------------
//多生产多消费,生产的苹果放容器中,但是容器中只能存放5个苹果
//JDK1.5后使用Lock代替同步
//公共资源类
import java.util.LinkedList;
import java.util.concurrent.locks.*;
class Box
{
	private final int MAX_SIZE = 5;//容器中存储最大容量
	private LinkedList <Object> list = new LinkedList<Object>();//存储容器
	//创建锁对象
	private final Lock lock= new ReentrantLock();
	//创建监视器对象
	private final Condition produce = lock.newCondition();
	private final Condition consume = lock.newCondition();

	//生产公共资源
	public void increase(){
		//获取锁
		lock.lock();
		try
		{
			while(list.size() > MAX_SIZE){
				System.out.println("...现在箱子中苹果的数量:"+list.size()+
					"箱子中的苹果超过5个,暂时不能执行任务!");
				try{produce.await();} catch(InterruptedException e){e.printStackTrace();}
			}
			list.add(new Object());
			System.out.println("...往箱子中放入1个苹果,现在箱子中苹果的数量:"+list.size());
			consume.signal();//唤醒消费者
		}
		finally
		{	
			//释放锁
			lock.unlock();
		}
	}

	//消费公共资源
	public void decrease(){
		//获取锁
		lock.lock();
		try
		{
			while(list.size() < 1){
				System.out.println("现在箱子中苹果的数量:"+list.size()+
					"箱子中苹果数量不足1个,暂时不能执行生产任务!");
				try{consume.await();} catch(InterruptedException e){e.printStackTrace();}
			}
			list.remove();
			System.out.println("从箱子中取出1个苹果,现在箱子中苹果的数量:"+list.size());
			produce.signal();//唤醒生产者
		}
		finally
		{
			//释放锁
			lock.unlock();
		}
	}

}
//生产者类
class Producer implements Runnable
{
	private Box box;
	Producer(Box box){
		this.box = box;
	}
	public void run(){
		while(true){
			try
			{
				Thread.sleep((long)(Math.random()*1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			box.increase();
		}
	}
}
//消费者类
class Consumer implements Runnable
{
	private Box box;
	Consumer(Box box){
		this.box = box;
	}
	public void run(){
		while(true){
			try
			{
				Thread.sleep((long) (Math.random()*1000));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			box.decrease();
		}	
	}
}
public class BoxAppleThread2
{
	public static void main(String[] args) 
	{
		//创建资源类对象
		Box box = new Box();
		//创建线程任务对象
		Producer pro = new Producer(box);
		Consumer con = new Consumer(box);
		//创建线程
		new Thread(pro).start();
		new Thread(con).start();
	}
}

发表于 2017-01-15 15:44:52 回复(1)
public class Test {
    public static void main(String[] args) {
        Box box = new Box();

        Product product = new Product(box);
        Custom custom = new Custom(box);

        product.start();
        custom.start();
    }
}

class Product extends Thread {
    private Box box;

    /**
     * 构造函数.
     * 
     */
    public Product(Box box) {
        this.box = box;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void run() {
        while (true) {
            box.put();
        }
    }
}

class Custom extends Thread {
    private Box box;

    /**
     * 构造函数.
     * 
     */
    public Custom(Box box) {
        this.box = box;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void run() {
        while (true) {
            box.get();
        }
    }

}

class Box {
    private Integer count = 0;

    public void put() {
        synchronized (this) {
            while (count > 0) {
                try {
                    notifyAll();
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (count < 1)
                    break;
            }
            count++;
            System.out.println("放入一个苹果");
        }
    }

    public void get() {
        synchronized (this) {
            while (count < 1) {
                try {
                    notifyAll();
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (count > 0)
                    break;
            }
            count--;
            System.out.println("拿出一个苹果");
        }
    }
}

发表于 2015-07-27 09:06:01 回复(0)

<p>voliate int apples=0;</p><p><br></p><p>new Thread(new Runnable (</p><p> public void run(){</p><p>while(true){ if(apples&lt;5){</p><p> apples++;</p><p> }}</p><p> }</p><p>)).start();</p><p><br></p><p>new Thread(new Runnable(</p><p> public void run(){</p><p>while (true){ if(apples&gt;0){</p><p> apples - -;}</p><p> }</p><p> }).start();</p><p><br></p><p><br></p><p><br></p><p><br></p>

编辑于 2020-06-06 01:46:03 回复(0)

//写入读取操作都将采用同步的形式进行
class BoundQueue<T> {
    private final T[] queue;
    private int tail;
    private int head;
    private int count;

    public BoundQueue(int capacity) {
        queue = (T[]) new Object[capacity];
    }
    public synchronized void put(T t) throws InterruptedException {
        while (isFull())
            wait();
        doPut(t);
        notifyAll();
    }

    public synchronized T take() throws InterruptedException {
        while (isEmpty())
            wait();
        T t = doTake();
        notifyAll();
        return t;
    }


    private synchronized final void doPut(T t) {
        queue[tail] = t;
        if(++tail == queue.length)
            tail = 0;
        ++count;
    }

    private synchronized final T doTake(){
       T t = queue[head];
        queue[head] = null;
        if(++head == queue.length)
            head = 0;
        --count;
        return t;
    }

    private synchronized final boolean isFull(){
        return count == queue.length;
    }

    private synchronized final boolean isEmpty(){
        return count == 0;
    }
}
编辑于 2015-10-14 17:53:36 回复(0)
李兴华那本书里有现成的
发表于 2015-08-12 13:30:18 回复(0)
多线程,生产者消费者问题。
发表于 2015-08-09 14:54:42 回复(0)
生产者/消费者?
发表于 2015-07-09 08:25:17 回复(0)