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条)

报告相同问题?

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?