1.使用thread启动一个线程执行耗时任务;
Thread t1 = new Thread(new MyThread());
t1.start();
2.使用Exectors创建线程池执行多个耗时任务;
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i=0;i<1;i++){
executorService.execute(new Runnable() {
public void run() {
System.out.println("test");
}
});
}
3.使用future方式执行异步耗时任务;
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
4.其他开源框架提供的异步方案(如asynchttpclient,httpasyncclient等);
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
HttpGet request = new HttpGet("http://abc/get");
Future<HttpResponse> future = httpclient.execute(request, null);
HttpResponse response = future.get();
System.out.println("Response: " + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = httpEntity.getContent();
try {
String body;
final StringBuilder sb = new StringBuilder();
final char[] tmp = new char[1024];
final Reader reader = new InputStreamReader(inputStream);
int l;
while ((l = reader.read(tmp)) != -1) {
sb.append(tmp, 0, l);
}
body = sb.toString();
System.out.println(body);
} finally {
inputStream.close();
EntityUtils.consume(httpEntity);
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
网友评论