1,ExecutorService结合线程池
package com.asyn;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorServiceTest {
private static ExecutorService executor = Executors.newFixedThreadPool(1);
public static void main(String[] args) {
asynTask();
synTask();
System.out.println(new Date() + " 主线程执行结束");
}
/**
* 异步执行的方法
*/
public static void asynTask() {
executor.execute(new Runnable() {
public void run() {
try {
// 模拟异步方法执行的过程,耗时10秒
Thread.sleep(10000);
System.out.println(new Date() + " 异步方法执行结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executor.shutdown();
}
/**
* 同步执行的方法
*/
public static void synTask() {
System.out.println(new Date() + " 同步方法执行结束");
}
}
运行结果:
2,FutureTask
package com.asyn;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class FutureTaskTest {
public static void main(String[] args) {
asynTask();
synTask();
System.out.println(new Date() + " 主线程执行完毕");
}
public static void asynTask() {
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(10000);
System.out.println(new Date() + " 异步方法执行完毕");
return 1;
}
});
Thread thread = new Thread(task);
thread.start();
}
public static void synTask() {
System.out.println(new Date() + " 同步方法执行完毕");
}
}
执行结果: