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