Callable和Future线程累计

本文通过对比使用Runnable与Callable的方式实现1000个线程进行累加操作,揭示了同步问题及线程池的正确使用方法。指出由于线程间共享变量未妥善处理导致结果不准确,并给出改进方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

群里一同胞发了一段1000个线程做累加的代码,用的是Runable与Thread来做累加 如下是他的代码:

/** 
 * Created by ZuoQB on 2015-07-29. 
 */  
public class ThreadPlus {  
  
    private    static  int value = 0;  
    public synchronized static void inc() {  
        value++;  
    }  
    public static void main(String arges[]) throws InterruptedException{  
        ExecutorService execu = Executors.newFixedThreadPool(10);  
        long start = System.currentTimeMillis();  
        for (int i = 0; i < 1000; i++) {  
            execu.execute(new Runnable() {  
                public void run() {  
                    ThreadPlus.inc();  
                    System.out.println(value);//add by me  
                }  
            });  
        }  
        execu.shutdown();  
        long end = System.currentTimeMillis();  
        System.out.println("------------------"+value);  
        System.out.println(end-start);  
    }  
}

最后运行的时候没有得到预期的结果1000。我在线程run()中添加了一句输出代码,

发现计算结果是有1000的,代码最后那句输出早早的执行了,其实当执行输出的时候那1000个线程还没有执行完成,所以输出结果不准确。

下面是我用的Future和Callable按照原来的逻辑修改后的代码。

import java.util.concurrent.*;

/**
 * Created by ZuoQB on 2015-07-29.
 */
public class ThreadTest implements Callable<Integer> {
    private    static volatile int value = 0;
    public synchronized static void inc() {
        value++;
    }

    @Override
    public Integer call() throws Exception {
        ThreadTest.inc();
        return value;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService execu = Executors.newFixedThreadPool(10);
        Future<Integer> future = null;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            future = execu.submit(new ThreadTest());
            try {
                System.out.println(future.get());
            } catch (Exception e) {
                System.out.println("here can catch Exception,the exception is "+e.getMessage());
                execu.shutdownNow();
            }
        }
        execu.shutdown();//reduce accept new task
        long end = System.currentTimeMillis();
        System.out.println("------------------"+future.get());
        System.out.println(end-start);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值