gpt4 book ai didi

java - 排序线程按照创建/启动的顺序运行

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:34 26 4
gpt4 key购买 nike

我怎样才能按照实例化的顺序对线程进行排序。例如我怎样才能让下面的程序按顺序打印数字 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();
}
}
}

最佳答案

听起来像你想要的<a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll%28java.util.Collection%29" rel="noreferrer noopener nofollow">ExecutorService.invokeAll</a> ,它将以固定顺序从工作线程返回结果,即使它们可能以任意顺序安排:

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();
}
}

}

关于java - 排序线程按照创建/启动的顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com