kes*_*v84 10 java multithreading synchronization
我如何按照实例化的顺序订购线程.如何让下面的程序按顺序打印数字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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
fin*_*nnw 12
听起来像你想要的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
"我实际上有一些我希望并行执行的部分,然后一旦生成结果,我想以一定的顺序合并结果." 谢谢,这澄清了你的要求.
您可以一次性运行它们,但重要的是在线程完成计算时按顺序获取结果.无论Thread#join()他们在哪个你想获得他们的结果,或只是顺序Thread#join()所有这些,然后遍历它们来获得他们的结果.
// Joins the threads back to the main thread in the order we want their results.
public class ThreadOrdering {
private class MyWorker extends Thread {
final int input;
int result;
MyWorker(final int input) {
this.input = input;
}
@Override
public void run() {
this.result = input; // Or some other computation.
}
int getResult() { return result; }
}
public static void main(String[] args) throws InterruptedException {
MyWorker[] workers = new MyWorker[10];
for(int i=1; i<=10; i++) {
workers[i] = new MyWorker(i);
workers[i].start();
}
// Assume it may take a while to do the real computation in the threads.
for (MyWorker worker : workers) {
// This can throw InterruptedException, but we're just passing that.
worker.join();
System.out.println(worker.getResult());
}
}
}
Run Code Online (Sandbox Code Playgroud)
简单地说,线程的调度是不确定的。
死域 - 不要点击http://www.janeg.ca/scjp/threads/scheduling.html
更长的答案是,如果您想这样做,您需要手动等待每个线程完成其工作,然后再允许另一个线程运行。请注意,以这种方式,所有线程仍将交错,但在您同意之前它们不会完成任何工作。看看同步保留字。