67,512
社区成员
发帖
与我相关
我的任务
分享
import static java.lang.Thread.sleep;
class Main
{
public static void main(String[] args) {
Resource r=new Resource();
input input=new input(r);
output output=new output(r);
new Thread(input).start();
new Thread(output).start();
}
}
class Resource
{
private String name;
private String sex;
private boolean flag=true;
public synchronized void set(String name,String sex) {
if (!flag)
try {this.wait();} catch (InterruptedException e) { }
this.name = name;
this.sex = sex;
flag = false;
this.notify();
/*
下面这段代码替换上面那段,为什么等待/唤醒机制失效了?
if (!flag)
{
try {this.wait();} catch (InterruptedException e) {}
}
else
{
this.name = name;
this.sex = sex;
flag = false;
this.notify();
}
*/
}
public synchronized void print() {
if (flag)
try {this.wait();} catch (InterruptedException e) { }
System.out.println(name + "\t\t" + sex);
flag = true;
this.notify();
}
}
class input implements Runnable
{
Resource r;
input(Resource r)
{
this.r=r;
}
public void run()
{
int x = 0;
while(true)
{
if(x==0)
{
r.set("mike","male");
}
else
{
r.set("mary","female");
}
x = (x+1)%2;
}
}
}
class output implements Runnable {
Resource r;
output(Resource r) {
this.r = r;
}
public void run() {
while (true) {
r.print();
}
}
}
public synchronized void set(String name,String sex) {
if (!flag)
try {this.wait();} catch (InterruptedException e) { }
this.name = name;
this.sex = sex;
flag = true;
this.notify();
/*
下面这段代码替换上面那段,为什么等待/唤醒机制失效了?
if (!flag)
{
try {this.wait();} catch (InterruptedException e) {}
}
else
{
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
*/
}
public synchronized void print() {
if (flag)
try {this.wait();} catch (InterruptedException e) { }
System.out.println(name + "\t\t" + sex);
flag = false;
this.notify();
}