日期:2014-05-20  浏览次数:20705 次

很有意思的一个题目:关于多线程!!


我今天自己写了一下这个小程序

这个题目的要求是   :
有4对家庭,分别有爸爸,妈妈,儿子,女儿

爸爸们专门负责往盘子里放苹果,妈妈们专门负责往盘子里放橘子,
儿子门专门吃盘子里的橘子;女儿们专门吃盘子里的苹果;

注意;盘子里最多只能有10个水果,而且每次只能放或者取一个水果;

就这么多了,代码在下面,运行出现了点问题,好象有时候   某些方法被访问多次,
有兴趣的可以运行一下代码,帮我分析一下原因,谢谢   了
class   ThreadTest
{

public   static   void   main(String[]   args)
{
Plate   q=new   Plate();
Father   f1=new   Father(q);
Father   f2=new   Father(q);
Father   f3=new   Father(q);
Father   f4=new   Father(q);

Mother   m1=new   Mother(q);
Mother   m2=new   Mother(q);
Mother   m3=new   Mother(q);
Mother   m4=new   Mother(q);

Son   s1=new   Son(q);
Son   s2=new   Son(q);
Son   s3=new   Son(q);
Son   s4=new   Son(q);

Daughter   d1=new   Daughter(q);
Daughter   d2=new   Daughter(q);
Daughter   d3=new   Daughter(q);
Daughter   d4=new   Daughter(q);

f1.start();
f2.start();
f3.start();
f4.start();

m1.start();
m2.start();
m3.start();
m4.start();

s1.start();
s2.start();
s3.start();
s4.start();

d1.start();
d2.start();
d3.start();
d4.start();
}
}

class   Father   extends   Thread
{
Plate   q;
Father(Plate   q)
{
this.q=q;
}
public   void   run()
{
while(true)
{
q.putApple(q.apple);
System.out.println(Thread.currentThread().getName()+ "   put   one   apple:  

the   number   of   apple   in   the   plate: "+q.apple);
}
}
}
class   Mother   extends   Thread
{
Plate   q;
Mother(Plate   q)
{
this.q=q;
}
public   void   run()
{
while(true)
{
q.putOrange(q.orange);
System.out.println(Thread.currentThread().getName()+ "   put   one  

orange:the   number   of   orange   in   the   plate: "+q.orange);
}
}
}
class   Son   extends   Thread
{
Plate   q;
Son(Plate   q)
{
this.q=q;
}
public   void   run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+ "   get   one   orange:the  

number   of   orange   in   the   plate: "+q.getOrange());
          }
}
}
class   Daughter   extends   Thread
{
Plate   q;
Daughter(Plate   q)
{
this.q=q;
}
public   void   run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+ "Daughter   get   one  

apple:the   number   of   apple   in   the   plate: "+q.getApple());
}
}
}
class   Plate
{

int   apple=0;
int   orange=0;
int   pFull=10;
public   synchronized   void   putApple(int   i)
{
if(pFull <11   &&   pFull> 0)
{
i++;
apple=i;