Java for线程循环一起开始(几乎同时) [英] Java for loop of threads starting together (almost same time)

查看:928
本文介绍了Java for线程循环一起开始(几乎同时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

 final CyclicBarrier gate = new CyclicBarrier(2);

    Thread t1 = new Thread() {
        public void run() {
            try {
                gate.await();
                for (int i = 0; i < 1000; i++) {
                    System.out.println("F1:" + i);
                }
            } catch (InterruptedException | BrokenBarrierException ex) {
                Logger.getLogger(TestFor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    Thread t2 = new Thread() {
        public void run() {
            try {
                gate.await();
                for (int i = 0; i < 1000; i++) {
                    System.out.println("F2:" + i);
                }
            } catch (InterruptedException | BrokenBarrierException ex) {
                Logger.getLogger(TestFor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    t1.start();
    t2.start();

我能够启动2个线程.现在我需要两个以上的线程,比方说50个.for循环中唯一更改的参数是System.out.println("F2:" + i);作为FX,其中X是线程数.

I am able to start the 2 threads. Now I need more than 2 threads, lets say 50. The only changing parameter in those for loops is System.out.println("F2:" + i); as FX where X is the number of the thread.

有什么办法可以在for循环中创建这50个线程?

Is there any way of making those 50 threads inside a for loop ?

推荐答案

您可以使用类似

List<Thread> tList = new ArrayList<Thread>();

for(int i = 0; i < 50; i++) {

    final int id = i;

    tList.add(new Thread() { 
             public void run() {
                 try {
                     gate.await();
                     for (int k = 0; k < 1000; k++) {
                         System.out.println("F" + id + ":" + k);
                     }
                 }
                 catch (InterruptedException | BrokenBarrierException ex) {
                     Logger.getLogger(TestFor.class.getName()).log(Level.SEVERE, null, ex);
                 }
              }
    });
}

您只需

for(Thread t : tList)
     t.start();

如果时间真的到了,也许单个线程的代码增加了,这将首先初始化所有线程,然后彼此直接启动,因此您无需考虑实际需要初始化的时间.

If it is really about time and maybe your code for a single Thread increases this will first initialize all of them and start them directly after each other, so you don't need to think about the time you actually need to initialize them.

这篇关于Java for线程循环一起开始(几乎同时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆