2013-10-24 53 views
0

我有10个不同的线程,我想同时启动。同时,我的意思不是按顺序开始它们(尽管这将会很接近)。在java中同时启动10个不同的线程

在java中实现这一点的最佳方法是什么?

+3

如果你需要它们全部在**精确**同时开始,使用'CountDownLatch'。 –

+3

如果你需要“足够接近”,只需开始连续十次 – DeadChex

+0

为什么所有的downvotes?这是一个完全有效的问题,需要澄清。 –

回答

4

准确无误:您无法在同一时间启动所有10个线程。 ms或ns的顺序会有所不同。你可以尽量减少这种差异。即使如此:如果内核数量少于线程数量,那么在第一对线程运行其第一条指令之前,第一对线程将完成一些工作。

+2

+1虽然这不是“过度” - 只是准确。 :-) – Gray

+0

那么,什么是“同一时间”取决于你可以或愿意测量的差异。对于很多人来说,同一个ms对于其他人来说是“同一时间”,而ps可能不够接近。 ;)但我会修改它。 – TheMorph

+0

在高负载情况下,可能无法启动线程,因此它们都开始“同时”执行。这些是很好的警告。 – Gray

0

有一个很好的例子,使用CountDownLatch在Javaspecialists时事通讯The Law of the Corrupt Politician

public class TestCorruption { 
    private static final int THREADS = 2; 
    private static final CountDownLatch latch = new CountDownLatch(THREADS); 
    private static final BankAccount heinz = new BankAccount(1000); 

    public static void main(String[] args) { 
    for (int i = 0; i < THREADS; i++) { 
     addThread(); 
    } 
    Timer timer = new Timer(true); 
    timer.schedule(new TimerTask() { 
     public void run() { 
     System.out.println(heinz.getBalance()); 
     } 

    }, 100, 1000); 
    } 

    private static void addThread() { 
    new Thread() { 
     { 
     start(); 
     } 

     public void run() { 
     latch.countDown(); 
     try { 
      latch.await(); 
     } catch (InterruptedException e) { 
      return; 
     } 
     while (true) { 
      heinz.deposit(100); 
      heinz.withdraw(100); 
     } 
     } 

    }; 
    } 

} 
0

这取决于你的电脑有核的数量,这些将在同一时间启动线程数,这是我在这里的第一个评论,所以我希望这是正确的。

import java.util.concurrent.CountDownLatch; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class Practica { 

    private static final int NUMTHREADS = 10; 

    public static void main(String[] args) { 
     CountDownLatch cdl = new CountDownLatch(NUMTHREADS); 
     ExecutorService executor = Executors.newFixedThreadPool(NUMTHREADS); 
     for (int i = 0; i < NUMTHREADS; i++) { 
      executor.submit(new Imp(cdl)); 
      cdl.countDown(); 
      System.out.println("one thread sumbmited "+cdl.getCount()); 
     } 
     System.out.println("All threads submmited"); 
     executor.shutdown(); 
    } 

} 

class Imp implements Runnable { 
    CountDownLatch cdl; 

    public Imp(CountDownLatch arg) { 
     this.cdl = arg; 
    } 

    @Override 
    public void run() { 
     try { 
      cdl.await(); 
      System.out.printf("STARTED %s at %d millis%n", 
        Thread.currentThread().getName(), 
        System.currentTimeMillis()); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
相关问题