java产生死锁原因,代码如下。
packagedemo;classResource2{privateStringname;privateintcount=1;privatebooleanflag=fal...
package demo;
class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
this.name = name;
count++;
flag = true;
notify();
}
public synchronized void out() {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + "\tname:" + name);
flag = false;
notify();
}
}
class Producer implements Runnable {
private Resource2 r;
public Producer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.set("小苍");
}
}
}
class Consumer implements Runnable {
Resource2 r;
public Consumer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource2 r = new Resource2();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
} 展开
class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
this.name = name;
count++;
flag = true;
notify();
}
public synchronized void out() {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + "\tname:" + name);
flag = false;
notify();
}
}
class Producer implements Runnable {
private Resource2 r;
public Producer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.set("小苍");
}
}
}
class Consumer implements Runnable {
Resource2 r;
public Consumer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource2 r = new Resource2();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
} 展开
1个回答
展开全部
你这个不是死锁,就是flag的判断有问题,每个线程都是自己把自己锁住了,当flag为true时,看以下两段代码:
public synchronized void set(String name) {
if (flag)
try {
wait();
public synchronized void out() {
if (flag)
try {
wait();
两个线程都在wait,当然卡住不动了。
看你的代码,把set那段改成这样应该就好了:
public synchronized void set(String name) {
if (!flag)
try {
wait();
public synchronized void set(String name) {
if (flag)
try {
wait();
public synchronized void out() {
if (flag)
try {
wait();
两个线程都在wait,当然卡住不动了。
看你的代码,把set那段改成这样应该就好了:
public synchronized void set(String name) {
if (!flag)
try {
wait();
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询