class Res{
private String name;
private String sex;
private boolean flag = false; //一开始是空的
/*就是这里,注释的代码和没有注释的代码哪里不一样*/
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){
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}else{
try{this.wait();}catch(InterruptedException e){}
}
}
public synchronized void get(){
if (!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(this.name + "..." +this.sex);
flag = false;
this.notify();
}
}
class Input extends Thread{
private Res r;
public Input(Res r){
this.r = r;
}
int x = 0;
public void run(){
while (true){
if (0 == x){
r.set("mike", "male");
}else{
r.set("Alice", "female");
}
x = (x + 1) % 2;
}
}
}
class Output extends Thread{
private Res r;
public Output(Res r){
this.r = r;
}
public void run(){
while (true){
r.get();
}
}
}
public class ThreadCallDemo {
public static void main(String[] args) {
Res r = new Res();
new Input(r).start();
new Output(r).start();
}
}
求大神解答。。非常感谢
private String name;
private String sex;
private boolean flag = false; //一开始是空的
/*就是这里,注释的代码和没有注释的代码哪里不一样*/
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){
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}else{
try{this.wait();}catch(InterruptedException e){}
}
}
public synchronized void get(){
if (!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(this.name + "..." +this.sex);
flag = false;
this.notify();
}
}
class Input extends Thread{
private Res r;
public Input(Res r){
this.r = r;
}
int x = 0;
public void run(){
while (true){
if (0 == x){
r.set("mike", "male");
}else{
r.set("Alice", "female");
}
x = (x + 1) % 2;
}
}
}
class Output extends Thread{
private Res r;
public Output(Res r){
this.r = r;
}
public void run(){
while (true){
r.get();
}
}
}
public class ThreadCallDemo {
public static void main(String[] args) {
Res r = new Res();
new Input(r).start();
new Output(r).start();
}
}
求大神解答。。非常感谢