阿里巴巴实习生笔试题目

用Java代码模拟实现:一个人不断往箱子里放苹果,另一个人不断从箱子里取苹果,箱子只能放5个苹果,苹果数量无限。要求不使用Java.util.concurrent包中的类。

 

package fangying;

import java.util.ArrayList;
import java.util.Random;

public class AppleThreadDemo {
	public static void main(String[] args) {
		ArrayList<Apple> al = new ArrayList<Apple>();
		AppleProducer ap = new AppleProducer(al);
		AppleConsumer ac = new AppleConsumer(al);
		new Thread(ap).start();
		new Thread(ac).start();
	}
}

class Apple {
	private int id;

	public Apple(int id) {
		this.id = id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return this.id;
	}

	public String toString() {
		return "Apple " + id;
	}
}

class AppleProducer implements Runnable {
	private ArrayList<Apple> al;

	public AppleProducer(ArrayList<Apple> al) {
		this.al = al;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(new Random().nextInt(3) * 1000);
				synchronized (this.al) {
					if (al.size() < 5) {
						Apple apple = new Apple(al.size() + 1);
						al.add(apple);
						System.out.println("放入苹果:" + apple);
					} else {
						System.out.println("箱子已满!");
					}
				}
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
		}
	}

}

class AppleConsumer implements Runnable {
	private ArrayList<Apple> al;

	public AppleConsumer(ArrayList<Apple> al) {
		this.al = al;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(new Random().nextInt(2) * 1000);
				synchronized (this.al) {
					if (al.size() > 0) {
						Apple ret = al.remove(al.size()-1);
						System.out.println("拿走苹果"+ret);
					} else {
						System.out.println("盒子为空!");
					}
				}
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
		}
	}
}

  

posted @ 2015-08-19 11:26  fangying  阅读(487)  评论(0编辑  收藏  举报