Friday, 10 January 2014

Thread output in certain order

package threadseq;

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<String> results = new ArrayList<String>();
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);
}
}

No comments: