在Java中用Concurrent来实现的并发,并不是真正的并发,其中有一定的时间差,我们用如下的程序进行检测。
import java.util.ArrayList; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.concurrent.*; class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { Random R = new Random(); long time = R.nextInt(10)+1; Thread.sleep(time*1000); return "This is the " + id + " thread and it sleep "+ time +"s"; } } public class CallableTest { public static void main(String[] args) throws InterruptedException,ExecutionException { ExecutorService exec = Executors.newFixedThreadPool(10); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); int ThreadNum = 10; int i; for (i = 0; i < ThreadNum; i++) { results.add(exec.submit(new TaskWithResult(i))); } Set set=new HashSet(); int n = ThreadNum; while(n!=0) { for(i = 0 ;i < ThreadNum; i++) { if (results.get(i).isDone()) { System.out.println("!!!!!!"+results.get(i).get()+"!!!!!!"); if(set.add(i)) --n; } else { System.out.println("Future of "+i+" result is not yet complete"); } } System.out.println("______________________________________"); } exec.shutdown(); } }
运行一次该程序,我们先看看其最终结果:
This is the 0 thread and it sleep 10s
This is the 1 thread and it sleep 9s
This is the 2 thread and it sleep 2s
This is the 3 thread and it sleep 1s
This is the 4 thread and it sleep 9s
This is the 5 thread and it sleep 5s
This is the 6 thread and it sleep 5s
This is the 7 thread and it sleep 1s
This is the 8 thread and it sleep 7s
This is the 9 thread and it sleep 5s
那么我们可以猜想到其完成顺序如下:
第一秒:3,7
第二秒:2
第五秒:5,6,9
第七秒:8
第九秒:1,4
第十秒:0
但我们可以从日志可以看出其真正的完成顺序:
3,7
2
6,9
5
8
4
1
0