我如何按照他们实例化的顺序订购线程.我如何使下面的程序按顺序打印数字1 … 10.
public class ThreadOrdering { public static void main(String[] args) { class MyRunnable implements Runnable{ private final int threadnumber; MyRunnable(int threadnumber){ this.threadnumber = threadnumber; } public void run() { System.out.println(threadnumber); } } for(int i=1; i<=10; i++){ new Thread(new MyRunnable(i)).start(); } } }
解决方法
听起来像你想要的
ExecutorService.invokeAll,它会以固定的顺序返回工作线程的结果,尽管它们可以按任意顺序排列:
import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadOrdering { static int NUM_THREADS = 10; public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); class MyCallable implements Callable<Integer> { private final int threadnumber; MyCallable(int threadnumber){ this.threadnumber = threadnumber; } public Integer call() { System.out.println("Running thread #" + threadnumber); return threadnumber; } } List<Callable<Integer>> callables = new ArrayList<Callable<Integer>>(); for(int i=1; i<=NUM_THREADS; i++) { callables.add(new MyCallable(i)); } try { List<Future<Integer>> results = exec.invokeAll(callables); for(Future<Integer> result: results) { System.out.println("Got result of thread #" + result.get()); } } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } finally { exec.shutdownNow(); } } }