实现callable()接口创建多线程,但是并没有共享target,这是为什么?
代码如下:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* 创建线程方法3
*
* 创建步骤:
* 1、创建Callable接口的实现类,并实现call()方法,该方法有返回值。
* 2、创建Callable实现类的实例,使用FutureTask来包装Callable对象,并且也封装了call()方法的返回值。
* 3、使用FutureTask作为Thread类的target创建并启动线程。
* 4、调用FutureTask对象的get()方法返回子线程执行结束后的返回值。
*
* public interface Future<V>
*
* public interface Callable<V>
*
* public interface RunnableFuture<V> extends Runnable, Future<V>
*
* public class FutureTask<V> extends Object implements RunnableFuture<V>
*
*Java5之后,提供了Callable接口,看起来像是Runnable接口的增强版:该接口提供call()方法来作为线程执行体。
* 与run()相比,call()方法更强大,该方法可以有返回值,并且可以声明抛出异常。
* 但是Callable不是Runnable接口的子类,不能作为Thread的target。而且call()方法返回的值如何调用呢?
*Java5给出了Future接口,来获得call()方法的返回值。
* 并提供了FutureTask实现类,该类实现了Runnale接口和Future接口---可以作为Thread类的target。
*
* FutureTask是Future接口的实现类。Future接口提供了一些方法来控制他关联的Callable任务。
* boolean cancel(boolean mayInterruptIfRunning) 试图取消该Future关联的Callable任务
* boolean isCancelled(); Returns {@code true} if this task was cancelled before it completed normally.
* boolean isDone(); Returns {@code true} if this task completed.
* V get(long timeout, TimeUnit unit);设置阻塞时间
* V get() ;返回call()方法的返回值,调用该方法将导致程序阻塞,必须等到子线程结束后才会有返回值
*
* @author WSS
* @date 2020-08-10 17:26
*/
public class CreateThreadMethod3 implements Callable<Integer> {
//实现call()方法,作为线程执行体
@Override
public Integer call(){
int i = 5;
for( ; i<200 ; i++){
System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
}
//call()方法可以有返回值
return i;
}
public static void main(String[] args) {
//创建Callable对象
CreateThreadMethod3 cd = new CreateThreadMethod3();
//使用FutureTask来包装Callable对象
FutureTask<Integer> task = new FutureTask<>(cd);
for(int i=0 ; i<40 ; i++){
System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
if(i==18){
//实质还是以Callable对象来创建并启动线程
new Thread(task,"有返回值的线程2").start();
new Thread(task,"有返回值的线程1").start();
}
}
try{
System.out.println("子线程1的返回值" + task.get());
System.out.println("子线程2的返回值" + task.get());
}catch(Exception e){
e.printStackTrace();
}
}
}
执行结果如下
一直到最后是这样
有哪位大佬能帮忙解释一下,为什么线程1没有打印语句?是没有执行吗?但是最后的get方法又有值。