package step2; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; // ---------------------Begin------------------------ //tips: 输出语句为:Thread.currentThread().getName()+"的call()方法在运行" //定义一个实现Callable接口的实现类,类名必须命名为MyThread_callable // ---------------------End------------------------ public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { // 创建Callable接口的实现类对象 MyThread_callable myThread3 = new MyThread_callable(); // 使用FutureTask封装Callable接口 FutureTask<Object> ft1 = new FutureTask<>(myThread3); // 使用Thread(Runnable target ,String name)构造方法创建线程对象 Thread thread1 = new Thread(ft1, "thread1"); // 创建并启动另一个线程thread2 FutureTask<Object> ft2 = new FutureTask<>(myThread3); Thread thread2 = new Thread(ft2, "thread2"); // ---------------------Begin------------------------ // 调用线程对象的start()方法启动线程 // 可以通过FutureTask对象的方法管理返回值 // ---------------------End------------------------ } }
时间: 2023-08-15 22:33:41 浏览: 32
代码中有一些错误,我来帮你指出来:
1. 在代码注释中,类名应该是 MyThread_callable 而不是 MyThread。
2. 在代码注释中,输出语句应该是 Thread.currentThread().getName() + "的call()方法在运行"。
3. 在代码注释中,应该使用 // 注释单行注释,而不是 /* ... */ 注释多行注释。
4. 在main方法中,创建线程对象时应该使用 new Thread(ft1, "thread1") 和 new Thread(ft2, "thread2") 而不是 new Thread(myThread3, "thread1") 和 new Thread(myThread3, "thread2")。
5. 在main方法中,调用线程对象的start()方法启动线程。
6. 在main方法中,可以通过FutureTask对象的方法管理返回值,正确的写法是:
```java
// 调用线程对象的start()方法启动线程
thread1.start();
thread2.start();
// 可以通过FutureTask对象的方法管理返回值
try {
Object result1 = ft1.get();
Object result2 = ft2.get();
System.out.println("线程1的返回值为:" + result1);
System.out.println("线程2的返回值为:" + result2);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)