多线程的问题,发生死锁

dongchaotiantian 2008-01-26 05:16:23
//定义一个生产类
class Producer extends Thread
{

Producer()
{
setPriority(Thread.MAX_PRIORITY);
}
public void run()
{
Store store = new Store();
for(int i=0;i<15;i++)
{
store.store_in();
}
}
}
//定义一个消费类
class Customer implements Runnable
{
long time = 100;
Customer()
{
}
public void run()
{
try{
Thread.sleep(time);
}catch (InterruptedException e){throw new RuntimeException(e);}
Store store = new Store();
for(int i=0;i<15;i++)
{
store.store_out();
}
}
}

public class Store
{
private static int productors = 0;
private final int MAX_STORE = 10;
private final int MIN_STORE = 1;
//定义一个同步入货方法
public synchronized void store_in()
{
if (productors >= MAX_STORE)
{
try {
System.out.println("库存数量太多!!!!!");
wait();
} catch (Exception e){}
}
else
{
productors ++;
System.out.println("执行入库,库存数量为"+ productors);
notifyAll();
}
}
//定义一个同步取货方法
public synchronized void store_out()
{
if (productors < MIN_STORE)
{
try {
System.out.println("库存数量不足!!!!!");
wait();
}catch (Exception e){}
}
else
{
productors --;
System.out.println("执行出库,库存数量为"+productors);
notifyAll();
}
}
//定义查库存方法
public int getStore()
{
return productors;
}
//主涵数,启动两个线程
public static void main(String args [])
{
Producer p = new Producer();
p.start();
Store store = new Store();

Thread c = new Thread(new Customer());
c.start();
System.out.println(store.getStore());
}
}
...全文
100 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizzz 2008-01-26
  • 打赏
  • 举报
回复
看了你的程序,我觉得不可能出现死锁的问题。因为你的程序里面根本就没有资源争用的情况。
生产者和消费者都使用了独立的Store对象,而且Store中方法的同步也是加在对象级别上的,不存在争用的情况,所以死锁就无从谈起。顶多是两个线程wait之后没有线程能够唤醒他们而已。再看你的main方法启动的两个线程都没有jion,主线程绝对不会等待他们处理完成就才结束,主线程退出导致程序退出就更不会有死锁的问题了。

只是看了一下程序做的判断,没有做实际的调试,有错之处还望见谅。
KK3K2005 2008-01-26
  • 打赏
  • 举报
回复
生产 消费 库存 各自有自己的store 看不出他们是一伙的

已经不是线程的问题了

死锁是因为c.run.store_out() 这里永远的 wait()

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧