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,明白了吗?
Input类的构造方法需要Res类型的参数
r是传的参数,方法的声明和调用参数要匹配。
调用构造函数需要传入的参数
Input(Res r) {
this.r = r;
}
r是参数类型,声明与调用要保持一致
r是参数,如楼上几位所说,调用构造方法需要传一个相同类型的参数才行.希望你能看一些java的基础视频,个人推荐传智的视频
构造方法分为有参和无参,new Input(r) 就是有参构造,也可以写成Input in=new Input(r); in.setR (r);
不过你要在Input里面写无参构造方法,再加上属性的get 和set方法。
构造方法,这个地方是把另外一个类的实例作为参数传递给Input.
含有参数的构造方法,因为你就是这么写的
Input(Res r) {
this.r = r;
}
如果你这里Input(){}的话就不用传入参数。
不过这段代码都到线程同步了,你怎么会知道线程同步而不知道构造器。可能不知道你的疑问具体在哪里
因为你的构造函数了 里就要求一个Res 参数