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

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

    Here's a way to do it without having a master thread that waits for each result. Instead, have the worker threads share an object which orders the results.

    import java.util.*;
    
    public class OrderThreads {
        public static void main(String... args) {
            Results results = new Results();
            new Thread(new Task(0, "red", results)).start();
            new Thread(new Task(1, "orange", results)).start();
            new Thread(new Task(2, "yellow", results)).start();
            new Thread(new Task(3, "green", results)).start();
            new Thread(new Task(4, "blue", results)).start();
            new Thread(new Task(5, "indigo", results)).start();
            new Thread(new Task(6, "violet", results)).start();
        }
    }
    
    class Results {
        private List results = new ArrayList();
        private int i = 0;
    
        public synchronized void submit(int order, String result) {
            while (results.size() <= order) results.add(null);
            results.set(order, result);
            while ((i < results.size()) && (results.get(i) != null)) {
                System.out.println("result delivered: " + i + " " + results.get(i));
                ++i;
            }
        }
    }
    
    
    class Task implements Runnable {
        private final int order;
        private final String result;
        private final Results results;
    
        public Task(int order, String result, Results results) {
            this.order = order;
            this.result = result;
            this.results = results;
        }
    
        public void run() {
            try {
                Thread.sleep(Math.abs(result.hashCode() % 1000)); // simulate a long-running computation
            }
            catch (InterruptedException e) {} // you'd want to think about what to do if interrupted
            System.out.println("task finished: " + order + " " + result);
            results.submit(order, result);
        }
    }
    

提交回复
热议问题