创建线程方式4-线程池
使用线程池的 submit()
或 execute()
方法提交任务。
execute(Runnable)
: 提交不需要返回值的任务。submit(Runnable/Callable)
: 提交任务,返回一个Future
对象,可以用来跟踪任务状态和获取结果。调用get()
方法可以获取Callable
返回的值
import java.util.concurrent.*;
public class FourTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("------------------主线程开始------------------");
// 这里我只实现了一个简单的线程池,如果正式使用不能用这个来实现线程池必须要用 new ThreadPoolExecutor();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new RunnableTest());
Future<String> submit = executorService.submit(new CallableTest());
System.out.println(submit.get());
executorService.shutdown();
}
}
class RunnableTest implements Runnable {
@Override
public void run() {
System.out.println("调用了 Runnable 的方法");
}
}
class CallableTest implements Callable<String> {
@Override
public String call() throws Exception {
return "我是 Callable 返回值";
}
}
结果:
------------------主线程开始------------------
调用了 Runnable 的方法
我是 Callable 返回值