how should i finish this package step2; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; // ---------------------Begin------------------------ //tips: 输出语句为:Thread.currentThread(
时间: 2023-08-15 20:46:37 浏览: 152
Java多线程之异步Future机制的原理和实现共5页.p
).getName() + ": " + i // 实现Callable接口来创建线程 class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); sum += i; } return sum; } } public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { // 创建Callable对象 MyCallable myCallable = new MyCallable(); // 将Callable对象封装成一个FutureTask对象 FutureTask<Integer> futureTask = new FutureTask<>(myCallable); // 创建线程并启动 Thread thread = new Thread(futureTask); thread.start(); // 获取线程执行结果 int result = futureTask.get(); System.out.println("线程执行结果为:" + result); } } // ----------------------End-------------------------
阅读全文