public 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) {
e.printStackTrace();
}
this.name=name;
this.sex=sex;
this.flag=true;
this.notify();
}
public synchronized void out(){
if(!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"...."+sex);
this.flag=false;
this.notify();
}
}
public class Input implements Runnable {
private Res r;
Input(Res r) {
this.r = r;
}
public void run() {
int x = 0;
while (true) {
if (x == 0) {
r.set("tom", "man");
} else {
r.set("李麗", "女");
}
x = (x + 1) % 2;
}
}
}
public class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class TestDemo {
public static void main(String[] args) {
Res r=new Res();//Res(String name, String sex)
Input in=new Input(r);//
Output out=new Output(r);//
Thread td1=new Thread(in);
Thread td2=new Thread(out);
td1.start();
td2.start();
}
}
Input in=new Input(r); 括號裡面為什麼放個r
在Input這類裡面,你如果聲明了一個帶參數的構造方法,而還想使用無參數的構造方法,需要同時聲明無參數構造方法,即在Input類裡面再寫:
Input(){
//這裡不需要寫任何代碼
}
這裡在TestDemo,裡面就可以使用Input in=new Input( ),但是這裡我們需要用帶參數的構造方法,因為run方法裡面需要使用到傳入的參數r,明白了嗎?