标签:
1.基础类-java.util.concurrent.ExcutorService
这个类的几个重要函数
shutdown 关闭任务池,无法传入新任务
shutdownnow 关闭所有任务,包括未执行完成的任务
submit 向任务池提交任务
2.基础接口-java.util.concurrent.Future
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
FutureTask 是实现了Future接口和Runnable接口,RunnableFuture接口
public
class
Test {
public
static
void
main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Task task =
new
Task();
Future<Integer> result = executor.submit(task);
executor.shutdown();
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(
"主线程在执行任务"
);
try
{
System.out.println(
"task运行结果"
+result.get());
}
catch
(InterruptedException e) {
e.printStackTrace();
}
catch
(ExecutionException e) {
e.printStackTrace();
}
System.out.println(
"所有任务执行完毕"
);
}
}
class
Task
implements
Callable<Integer>{
@Override
public
Integer call()
throws
Exception {
System.out.println(
"子线程在进行计算"
);
Thread.sleep(
3000
);
int
sum =
0
;
for
(
int
i=
0
;i<
100
;i++)
sum += i;
return
sum;
}
}
public
class
Test {
public
static
void
main(String[] args) {
//第一种方式
ExecutorService executor = Executors.newCachedThreadPool();
Task task =
new
Task();
FutureTask<Integer> futureTask =
new
FutureTask<Integer>(task);
executor.submit(futureTask);
executor.shutdown();
//第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
/*Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
Thread thread = new Thread(futureTask);
thread.start();*/
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(
"主线程在执行任务"
);
try
{
System.out.println(
"task运行结果"
+futureTask.get());
}
catch
(InterruptedException e) {
e.printStackTrace();
}
catch
(ExecutionException e) {
e.printStackTrace();
}
System.out.println(
"所有任务执行完毕"
);
}
}
class
Task
implements
Callable<Integer>{
@Override
public
Integer call()
throws
Exception {
System.out.println(
"子线程在进行计算"
);
Thread.sleep(
3000
);
int
sum =
0
;
for
(
int
i=
0
;i<
100
;i++)
sum += i;
return
sum;
}
}
----------------------------------------------------------------------------
测试函数
public static void main(String[] args) {
System.out.println(new Date());
StaticMethod.getResult_Asynchronous("http://cs.jiwu.com/build!home.action?bid=3343", "");
System.out.println(new Date());
System.out.println(new Date());
StaticMethod.getResult("http://cs.jiwu.com/build!home.action?bid=3343", "");
System.out.println(new Date());
}
输出结果:
Fri Apr 15 14:41:22 CST 2016
Fri Apr 15 14:41:22 CST 2016
Fri Apr 15 14:41:22 CST 2016
Fri Apr 15 14:41:32 CST 2016
---------------------------------------------------------------------------------------------------------
结论:采用异步方式更新一个楼盘页 几乎不需要等待,而采用同步方式却花费了10s的时间,性能有巨大差距!
标签:
原文地址:http://www.cnblogs.com/jiwuyf/p/5395466.html