我有这个程序,其中两个线程等待相同的锁定库存对象并导致程序挂起。但Thread1并不是为了锁定Thread2,反之亦然。如果这不是死锁,那么这种情况会怎样?
public class DeadlockSimulator {
public static void main(String[] args) {
Stock st = new Stock();
Runnable p1 = new Producer(st);
Runnable c1 = new Consumer(st);
Thread t1 = new Thread(p1);
Thread t2 = new Thread(c1);
t1.start();
t2.start();
}
}
public class Producer implements Runnable{
private final Stock st;
public Producer(Stock st) {
this.st=st;
}
@Override
public void run() {
try{
while(true)
st.addStock(3);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class Stock {
private int qoh;
public Stock() {
}
public synchronized int getStock(int required) throws InterruptedException
{
int take=0;
if(qoh> required)
{
qoh=qoh-required;
take=required;
//notify();
}
else
{
wait();
}
return take;
}
public synchronized void addStock(int stocks) throws InterruptedException
{
if(qoh >7)
{
wait();
}
else
{
qoh=qoh+stocks;
System.out.println("Current Stock"+ qoh);
// notify();
}
}
public int getorderLevel()
{
return this.qoh;
}
}
public class Consumer implements Runnable {
private final Stock st;
public Consumer(Stock st) {
this.st = st;
}
@Override
public void run() {
try {
while (true) {
int got = st.getStock(5);
System.out.println("Got =" + got);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
你是对的:这不是死锁的例子 这是synchronization的一个示例,它是concurrency control的一种形式 在Java中,生产者/消费者问题通常通过使用BlockingQueue来解决。