本关任务:编写使用Callable接口重写call()方法,方法体为输出5遍“Thread.currentThread().getName() +“的call()方法在运行"”,循环结束后返回线程的名字。
时间: 2024-03-25 16:37:24 浏览: 28
好的,下面是使用Callable接口重写call()方法的示例代码:
```java
import java.util.concurrent.*;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "的call()方法在运行");
}
return Thread.currentThread().getName();
}
public static void main(String[] args) throws Exception {
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newCachedThreadPool();
Future<String> future = executor.submit(callable);
System.out.println("返回结果:" + future.get());
executor.shutdown();
}
}
```
在这个示例中,我们定义了一个实现了Callable接口的MyCallable类,并重写了call()方法。在call()方法中,我们使用循环输出5遍“Thread.currentThread().getName() +“的call()方法在运行"”,并在循环结束后返回线程的名字。
然后,在main()方法中,我们创建了一个MyCallable对象,将其作为参数传递给ExecutorService的submit()方法,从而创建了一个Future对象。我们通过调用Future对象的get()方法来获取线程执行完后的返回结果,并输出该结果。
最后,我们调用ExecutorService的shutdown()方法关闭线程池。