Java 死锁是否需要两个线程互相等待资源?
我有一个程序,其中两个线程等待同一个锁库对象,并导致程序挂起。但螺纹1不适用于锁紧螺纹2,反之亦然。如果这不是僵局,这种情况叫什么Java 死锁是否需要两个线程互相等待资源?,java,multithreading,deadlock,Java,Multithreading,Deadlock,我有一个程序,其中两个线程等待同一个锁库对象,并导致程序挂起。但螺纹1不适用于锁紧螺纹2,反之亦然。如果这不是僵局,这种情况叫什么 public class DeadlockSimulator { public static void main(String[] args) { Stock st = new Stock(); Runnable p1 = new Producer(st); Runnable c1 = new Consume
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();
}
}
}
你是对的:这不是死锁的例子。
它是的一个示例,是的一种形式。
在Java中,生产者/消费者问题通常通过使用解决。这是两个线程等待单个资源的示例,
库存。
不是死锁。程序挂起是因为在run()中有一个无限循环