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

前端 未结 10 1206
礼貌的吻别
礼貌的吻别 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:51

    "I actually have some parts that i want to execute in parallel, and then once the results are generated, I want to merge the results in certain order." Thanks, this clarifies what you're asking.

    You can run them all at once, but the important thing is to get their results in order when the threads finish their computation. Either Thread#join() them in the order in which you want to get their results, or just Thread#join() them all and then iterate through them to get their results.

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

提交回复
热议问题