本帖最后由 hoyouly 于 2013-8-29 23:05 编辑
如题,我改了一下生产者和消费者例子,在eclipse上能运行,可是在虚拟机上去报错,这是个怎么情况,源代码如下:
主函数:
package threadTest;
/*
* 假设现在有这么一个箱子,里面有5个苹果,现在有三个人要吃苹果,一次只能拿一个,
* 还有两个人往里面放苹果,一次也只能放一个,直到箱子里空了,就结束
*/
public class AppleSumTest {
public static void main(String []args)
{
AppleSum as=new AppleSum();
EatThread eat=new EatThread(as);
PutThread put=new PutThread(as);
Thread put1=new Thread(put);
put1.start();
Thread put2=new Thread(put);
put2.start();
Thread eat1=new Thread(eat);
eat1.start();
Thread eat2=new Thread(eat);
eat2.start();
Thread eat3=new Thread(eat);
eat3.start();
}
}
资源函数:
public class AppleSum {
//定义原本篮子中苹果有5个
private static int sum=5;
//定义标记位
boolean flag=false;
//同步函数,吃苹果
public synchronized void eatApple()
{
if(!flag)
{
try
{
this.wait();
}catch(Exception e){
System.out.println("吃苹果等待异常");
}
}
System.out.println(Thread.currentThread().getName()+" 吃了一个苹果,现在篮子中苹果个数是:"+(--sum));
if(sum<=0)
System.exit(0);
flag = false;
this.notifyAll();
}
public synchronized void putApple()
{
if(flag)
{
try
{
this.wait();//wait方法中抛出了异常,故需要捕获异常
}catch(Exception e){
System.out.println("PutApple等待异常");
}
}
System.out.println(Thread.currentThread().getName()+" 放进去一个苹果,现在篮子中苹果个数是:"+(++sum));
flag = true;
this.notifyAll();
}
}
吃苹果线程
package threadTest;
public class EatThread implements Runnable {
private AppleSum as;
public EatThread(AppleSum as)
{
this.as=as;
}
public void run()
{
while(true)
{
as.eatApple();
}
}
}
放苹果线程
package threadTest;
public class PutThread implements Runnable {
private AppleSum as;
public PutThread(AppleSum as)
{
this.as=as;
}
public void run()
{
while(true)
{
as.putApple();
}
}
}
在eclipse运行结果正常,可是当我再虚拟机上运行的是,却出现这样的错误
这是个怎么情况
|
|