浅析Java中Concurrent的并发时间问题

    在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

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值