yihuanxuri 2015-10-15 23:59 采纳率: 100%
浏览 1607
已采纳

初学Java有句话看不懂

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

  • 写回答

10条回答 默认 最新

  • im大钊 2015-10-16 01:11
    关注

    在Input这类里面,你如果声明了一个带参数的构造方法,而还想使用无参数的构造方法,需要同时声明无参数构造方法,即在Input类里面再写:
    Input(){
    //这里不需要写任何代码
    }
    这里在TestDemo,里面就可以使用Input in=new Input( ),但是这里我们需要用带参数的构造方法,因为run方法里面需要使用到传入的参数r,明白了吗?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决