import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * 用多線程去處理 "123","456","789" 三個字符串,而後以"147","258","369"輸出 * */ public class ThreadSample { public static void main(String[] args) throws InterruptedException, ExecutionException { String str1 = "123",str2 = "456",str3 = "789"; ProcessThread thread3 = new ProcessThread(str3, null); ProcessThread thread2 = new ProcessThread(str2, thread3); ProcessThread thread1 = new ProcessThread(str1, thread2); for (int i = 0; i < str1.length(); i++) { thread1.setIndex(i); FutureTask<String> future = new FutureTask<String>(thread1); new Thread(future).start(); String outStr = future.get(); System.out.println(outStr); } } }
輸出:
147
258
369
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class ProcessThread implements Callable<String>{ private String value; private ProcessThread next; private Integer index; public String call() throws Exception { if(this.next!=null){ this.next.setIndex(this.index); //開啓下一個線程 FutureTask<String> future = new FutureTask<String>(this.next); new Thread(future).start(); String nextString = future.get(); return value.charAt(this.index)+nextString; } return String.valueOf(value.charAt(this.index)); } public ProcessThread(String value, ProcessThread next) { this.value = value; this.next = next; } //set/get 省略 }