qq_27368885 2015-05-05 04:19 采纳率: 25%
浏览 3363

java怎么用多线程并发运行for?

如果把下面的改成十个线程并发运行不同的for语句,,就我最下面写好的那个方法,参数用定义好的数组里面的十个int变量,请问要怎么写?

 public static void main(String[] args) {   
            for(Thread t:getThreads()){
                t.start();
            }
        }
        public static Thread[] getThreads(){
            Thread[] thread = new Thread[10];
            for(int i=0;i<10;i++){
                final Integer num = new Integer(i);
                thread[i] = new Thread(new Runnable(){
                    public void run() {
                        int j=5;
                        while(j-->0){                       
                            System.out.println("this is thread"+num);   
                        }                                   
                    }
                });
            }
            return thread;
        }

        public static void  bbq(int a){
            for(int b=a;b<a+2;b++){
                System.out.println("for循环"+"起始值为"+a+"终止值为"+(a+2));
            }
            }
  • 写回答

2条回答 默认 最新

  • danielinbiti 2015-05-05 05:10
    关注
     for(Thread t:getThreads()){
                    t.start();
                }
                            因为线程执行时间太短了,用循环模拟不出效果来。
                            改成下面的方式
        Thread[] thread =getThreads()   ;
        thread[0].start();
        thread[1].start();
        thread[2].start();
        thread[3].start();
        thread[4].start();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献