package com.threeKindThreads;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestCallableThread implements Callable<Integer>{
private int i;
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
for(; i<100; i++) {
System.out.println(Thread.currentThread() + " " + i);
}
return i;
}
public static void main(String[] args) {
TestCallableThread thread = new TestCallableThread();
FutureTask<Integer> task1 = new FutureTask<Integer>(thread);
FutureTask<Integer> task2 = new FutureTask<Integer>(thread);
for(int i=0; i<100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if(i == 20) {
new Thread(task1, "Thread1 with return value").start();
new Thread(task2, "Thread2 with return value").start();
}
}
try {
System.out.println("return value = " + task1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
用Callable接口实现多线程
最新推荐文章于 2022-09-19 09:56:36 发布