Ordering threads to run in the order they were created/started

前端 未结 10 1191
礼貌的吻别
礼貌的吻别 2020-11-30 06:15

How can i order threads in the order they were instantiated.e.g. how can i make the below program print the numbers 1...10 in order.

public class ThreadOrder         


        
10条回答
  •  失恋的感觉
    2020-11-30 06:38

    Sounds like you want ExecutorService.invokeAll, which will return results from worker threads in a fixed order, even though they may be scheduled in arbitrary order:

    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 {
                private final int threadnumber;
    
                MyCallable(int threadnumber){
                    this.threadnumber = threadnumber;
                }
    
                public Integer call() {
                    System.out.println("Running thread #" + threadnumber);
                    return threadnumber;
                }
            }
    
            List> callables =
                new ArrayList>();
            for(int i=1; i<=NUM_THREADS; i++) {
                callables.add(new MyCallable(i));
            }
            try {
                List> results =
                    exec.invokeAll(callables);
                for(Future result: results) {
                    System.out.println("Got result of thread #" + result.get());
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
            } finally {
                exec.shutdownNow();
            }
        }
    
    }
    

提交回复
热议问题