JAVA多线程的并发控制

java的多线程实现主要有两种,一种是继承Thread,一种是实现Runnable接口,这个是java最基本的多线程知识。这里要补充一下,runnable接口中的run方法是不返回任何内容的,如果想返回一个对象可以试试用concurrent包中的Callable接口来替换runable接口的实现Executor.submit(Callable instance) 将返回一个Futrue<?>实例.

这里举个简单的例子

线程类要实现

public class ReadInforWork implements Callable<HashMap>

其中执行方法

    @Override
    public HashMap call() throws Exception {
        try {
            long time1=new java.util.Date().getTime();
            XXXX
            long time2=new Date().getTime();
            System.out.println(time2+" "+time1+" "+(time2-time1)+" "+reuslt.size());
            return reuslt;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

主线程使用如下方法调用,其中get就是拿到Future对象

 for(int i=0;i<read_info_thread_num;i++){
            ReadInforWork readInforWork=new ReadInforWork(read_info_thread_num,i,read_info_total_num);
            FutureTask<HashMap> readWorkThread = new FutureTask<HashMap>(readInforWork);
            new Thread(readWorkThread).start();
            HashMap result =readWorkThread.get();
            System.out.println(result.size());
        }

另外,还可以使用ExecutorServcie来实现。这里也是简单的举个例子

主线程调用方法为

        ExecutorService executorService= Executors.newCachedThreadPool();
        CompletionService<HashMap> completionService=new ExecutorCompletionService<HashMap>(executorService);
        for(int i=0;i<read_info_thread_num;i++){
            ReadInforWork readInforWork=new ReadInforWork(read_info_thread_num,i,read_info_total_num);
            completionService.submit(readInforWork);
        }
        for(int i=0;i<read_info_thread_num;i++){
           HashMap result=completionService.take().get();
           System.out.println(result.size());
        }

使用ExecutorService后就不需要在main函数中控制线程的结束时间了,如果不使用这个类,可以使用concurrent中的countdownLunch

这里是执行线程的写法,在执行完动作后操作下对应的countdownlunch即可

 @Override
    public void run() {
        try {
            long time1=new java.util.Date().getTime();
            XXXX
            long time2=new Date().getTime();
            System.out.println(time2+" "+time1+" "+(time2-time1)+" "+reuslt.size());
            countDownLatch.countDown();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

主函数写法如下

 CountDownLatch read_info_countdownlatch=new CountDownLatch(read_info_thread_num);
 
 read_info_countdownlatch.await();

另外还有一种写法是利用cyclickBarrier

参考文档 http://blog.csdn.net/xiao__gui/article/details/9213413


转载于:https://my.oschina.net/zimingforever/blog/371559

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值