//定义一个生产类
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());
}
}
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());
}
}
生产者和消费者都使用了独立的Store对象,而且Store中方法的同步也是加在对象级别上的,不存在争用的情况,所以死锁就无从谈起。顶多是两个线程wait之后没有线程能够唤醒他们而已。再看你的main方法启动的两个线程都没有jion,主线程绝对不会等待他们处理完成就才结束,主线程退出导致程序退出就更不会有死锁的问题了。只是看了一下程序做的判断,没有做实际的调试,有错之处还望见谅。