whh6888 2016-07-26 07:29 采纳率: 20%
浏览 1036

关于多线程以及函数传值的问题

大家好,现在在学习多线程,遇到一些问题,请教大家!
首先,代码如下
1. 类MyBean
public class MyBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

  1. 线程类 MyThread
    public class MyThread extends Thread{
    String id;
    CopyOnWriteArrayList MyBeanList;

    public MyThread(String ID,CopyOnWriteArrayList MyBeanLIST) {
    super();
    this.id=ID;
    this.MyBeanList=MyBeanLIST; //注释3
    }

    public void run(){ //注释4
    if (id.equals("1")) {
    MyBean myBean=new MyBean();
    myBean.setAge(20);
    myBean.setName("张三");
    MyBeanList.add(myBean);
    }else if (id.equals("2")) {
    MyBean myBean=new MyBean();
    myBean.setAge(18);
    myBean.setName("李四");
    MyBeanList.add(myBean);
    }
    }
    }

  2. 主函数
    public static void main(String[] args) throws InterruptedException {
    CopyOnWriteArrayList list= new CopyOnWriteArrayList();
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    int[] id={1,2};
    for (int i = 0; i < id.length; i++) {
    if (id[i]==1) {
    MyThread thread=new MyThread("1",list); // 注释1
    executorService.execute(thread);
    }else if (id[i]==2) {
    MyThread thread=new MyThread("2",list); // 注释2
    executorService.execute(thread);
    }
    }
    executorService.shutdown();
    while(true){
    if(executorService.isTerminated()){
    System.out.println("所有计算完毕!");
    break;
    }
    Thread.sleep(1000);
    }
    System.out.println("共有:"+list.size());
    }

请问:
(1)在函数传值的时候,即 注释1、注释2 处,传入的list是main函数中的一个变量,传入new MyThread()函数之后,即到了 注释3 处,this.MyBeanList=MyBeanLIST; MyBeanLIST; 就是刚刚传入的list,即将list赋值给this.MyBeanList,那么在此之后,list应该就与this.MyBeanList无关了。MyBeanList最后的siez为2,而程序最后输出的结果也是2,按照我的理解,MyBeanList的size为2,list与MyBeanList无关,则list的size应该为0 啊,为什么最后list的size也为2 呢?
(2)在调试多线程程序时,如何进入run()方法,也即 注释4 处?因为这里才是程序的主要部分,但是我断点在注释4 这里,好像程序执行时直接跳过了,没有进入run()方法,大家在调试多线程程序时,有什么好方法呢?

希望得到大家的指点,谢谢大家!

  • 写回答

1条回答 默认 最新

  • 关注
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值