本帖最后由 卢祥洲 于 2013-5-28 16:21 编辑
毕老师讲的多线程通讯第一个视频中,Input和Output类使用同一个对象:毕老师说用引用代替单例模式,想请教大家这引用怎么是同一个对象呢?- class Resource{
- String name;
- String sex;
- }
- class Input implements Runnable{
- private Resource r;//引用1、代替单例模式
- Input(Resource r){
- this.r = r;
- }
- public void run(){
- int x= 0;
- while(true){
- if(x==0){
- r.name = "lili";
- r.sex = "girl";
- } else{
- r.name = "龟龟";
- r.sex = "男";
- }
- x = (x+1)%2;
- }
- }
- }
- class Output implements Runnable{
- private Resource r;//引用2、代替单例模式
- Output(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- System.out.println(r.name+"******"+r.sex);
- }
- }
- }
- class InputOutputDemo03{
- public static void main(String[] args){
- Resource r = new Resource();
-
- Input in = new Input(r);
- Output out = new Output(r);
-
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
-
- t1.start();
- t2.start();
- }
- }
复制代码 |