public static void main(String[] args) throws InterruptedException, ExecutionException {
//1、thread实现线程
Thread t1 = new CustomThread.MyThreadDemo();
t1.start();
System.out.println(2222);
//2、利用runnable实现线程
Thread t2 = new Thread(new MyRunDemo());
t2.start();
//3、利用线程池 future callable 实现线程
FutureTask<String> ft = new FutureTask<String>(new MyCallDemo());
Executors.newSingleThreadExecutor().execute(ft);
System.out.println(ft.isDone());
if (ft.isDone()) {
System.out.println(ft.get());
}
System.out.println(ft.get());
}
public class FutureTest {
public static void main(String[] args) {
try {
Calc cal = new Calc();
System.out.println(cal.call());
FutureTask<Integer> ft = new FutureTask<>(cal);
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
ft.run();
} catch (Exception e1) {
System.out.println(e1.getMessage());
}
}).start();
System.out.println(ft.get());
} catch (Exception e) {
System.out.println("-------:" + e.getMessage());
}
}
public static class Calc implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return cal(10);
}
public static int cal(int num) {
int sum = 0;
for (int i = 0; i < num; i++) {
sum += i;
}
return sum;
}
}
}