java的多线程实现主要有两种,一种是继承Thread,一种是实现Runnable接口,这个是java最基本的多线程知识。这里要补充一下,runnable接口中的run方法是不返回任何内容的,如果想返回一个对象可以试试用concurrent包中的Callable接口来替换runable接口的实现Executor.submit(Callable instance) 将返回一个Futrue>实例.
这里举个简单的例子
线程类要实现
public class ReadInforWork implements Callable
其中执行方法
@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
ReadInforWork readInforWork=new ReadInforWork(read_info_thread_num,i,read_info_total_num);
FutureTask readWorkThread = new FutureTask(readInforWork);
new Thread(readWorkThread).start();
HashMap result =readWorkThread.get();
System.out.println(result.size());
}
另外,还可以使用ExecutorServcie来实现。这里也是简单的举个例子
主线程调用方法为
ExecutorService executorService= Executors.newCachedThreadPool();
CompletionService completionService=new ExecutorCompletionService(executorService);
for(int i=0;i
ReadInforWork readInforWork=new ReadInforWork(read_info_thread_num,i,read_info_total_num);
completionService.submit(readInforWork);
}
for(int i=0;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