CallableとFutureによるスレッドの作成
1941 ワード
:
public class CallableThreadTest implements Callable {
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" i "+i);
if(i==20)
{
new Thread(ft," ").start();
}
}
try
{
System.out.println(" :"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
:
public class Test1 implements Callable{
public String call() throws Exception {
System.out.print(" 1:"+Thread.currentThread().getName());
return null;
}
public static void main(String [] args){
FutureTask b =new FutureTask(new Test1());
Thread a =new Thread(b);
a.start();
System.out.println(" 2:"+Thread.currentThread().getName());
}