【发布时间】:2017-11-27 14:28:31
【问题描述】:
我是java新手,用wait() notify()学习java中线程的通信,发生了一些愚蠢的事情:
事情是这样的:我想用多线程不断地设置人类和获取人类,这意味着结果是(杰克男,玛丽女,杰克男,玛丽女......)
这是我的代码:
class Human {
private String name;
private String sex;
private boolean b = false;
public synchronized void set(String name, String sex) {
if (b) {
try {
this.wait();
} catch (InterruptedException e) {}
}
this.name = name;
this.sex = sex;
b = true;
this.notify();
}
public synchronized void get() {
if (!b) {
try {
this.wait();
} catch (InterruptedException e) {}
}
System.out.println(name+" "+sex);
b = false;
this.notify();
}
}
class SetHuman implements Runnable {
private Human h;
SetHuman(Human h) {
this.h = h;
}
public void run() {
int x = 0;
while(true) {
if (x==0) {
h.set("Jack","male");
} else {
h.set("Mary","female");
}
x = (x+1)%2;
}
}
}
class GetHuman implements Runnable {
private Human h;
GetHuman(Human h) {
this.h = h;
}
public void run() {
while (true) {
h.get();
}
}
}
class HumanDemo {
public static void main(String[]args) {
Human h = new Human();
SetHuman sh = new SetHuman(h);
GetHuman gh = new GetHuman(h);
Thread t1 = new Thread(sh);
Thread t2 = new Thread(gh);
t1.start();
t2.start();
}
}
当我运行 HumanDemo 时,它起作用了:result
然后,我在我的同步函数set()和get()中添加了一个else判断,这件事发生了:
public synchronized void set(String name, String sex) {
if (b) {
try {
this.wait();
} catch (InterruptedException e) {}
} else {
this.name = name;
this.sex = sex;
b = true;
this.notify();
}
}
public synchronized void get() {
if (!b) {
try {
this.wait();
} catch (InterruptedException e) {}
} else {
System.out.println(name+" "+sex);
b = false;
this.notify();
}
}
这是为什么?有人请告诉我为什么?谢谢你^-^!
【问题讨论】:
-
您能在不使用图像的情况下解释问题吗?这个不清楚
-
哦,对不起,我的意思是我需要将这两个人类打印一个,(杰克男,玛丽女,杰克男,玛丽女......)第一个工作,但是第二个,我加了else判断后,synchronized方法出了问题,就变成不同步了。
标签: java multithreading synchronized