题目描述:
用Java模拟一个拿苹果与放苹果的过程。现有一个苹果盒子,最多容纳5个苹果。一个人一直向盒子中放苹果,另一个人一直从盒子中拿苹果。
思路:
典型的生产者与消费者的多线程问题。
class AppleBox{//苹果盒子类,包含放进苹果、拿出苹果的方法
private int i = 0;
public synchronized void addApple()
{
if(i>=5)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {//方便观察
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
System.out.println("放进一个苹果,总共:"+i);
this.notify();
}
public synchronized void deApple()
{
if(i<=0)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try { //方便观察
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i--;
System.out.println("拿出一个苹果,还剩:"+i);
this.notify();
}
}
class Person1 implements Runnable{//放进苹果线程
private AppleBox applebox = null;
Person1(AppleBox a)
{
applebox = a;
}
public void run()
{
while(true)
applebox.addApple();
}
}
class Person2 implements Runnable{//拿出苹果线程
private AppleBox applebox = null;
Person2(AppleBox a){
applebox = a;
}
public void run()
{
while(true)
applebox.deApple();
}
}
public class ThreadDemo {
public static void main(String args[])//主方法
{
AppleBox a = new AppleBox();
Person1 per1 = new Person1(a);
Person2 per2 = new Person2(a);
new Thread(per1).start();
new Thread(per2).start();
}
}