JAVA多線程的併發控制|java多線程併發實例

java的多線程實現主要有兩種,一種是繼承Thread,一種是實現Runnable接口,這個是java最基本的多線程知識。這裏要補充一下,runnable接口中的run方法是不返回任何內容的,若是想返回一個對象能夠試試用concurrent包中的Callable接口來替換runable接口的實現Executor.submit(Callable instance) 將返回一個Futrue<?>實例.java

這裏舉個簡單的例子多線程

線程類要實現ide

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對象ui

 

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來實現。這裏也是簡單的舉個例子spa

主線程調用方法爲.net

     

  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便可code

 

@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();
        }
    }

主函數寫法以下orm

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

另外還有一種寫法是利用cyclickBarrier  參考文檔 http://blog.csdn.net/xiao__gui/article/details/9213413

相關文章
相關標籤/搜索