Callable interfaces implemented and used in conjunction with the Future


Implementation steps:

Create Callable interface implementation class, and implements call () method, the call () method as a thread of execution, and return values.

Callable create an instance of the implementation class, using packaging Callable FutureTask class object, which object encapsulates FutureTask Callable object of the call () method returns the value.

Use FutureTask Thread object as a target object to create and start a new thread.

Call Tread object start () method to start a thread, call FutureTask object get () method to obtain the return value after the end of the sub-thread execution.

Example:

public class CallableThreadTest implements Callable<Integer> {
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {

FutureTask<Integer> ft = new FutureTask<>(new CallableThreadTest(http://www.amjmh.com/v/));
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==20)
{
new Thread(ft).start();
}
}

System.out.println ( "child threads Return Value:" + ft.get ());

}
}

Guess you like

Origin www.cnblogs.com/liyanyan665/p/11359758.html