1.
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Main {
private static class Ch {};
public static void main(String[] args) throws Exception{
Callable<Ch> onlineChopping = new Callable<Ch>() {
public Ch call() throws Exception {
System.out.println("ch:start");
Thread.sleep(5000);
System.out.println("ch:ok");
return new Ch();
}
};
FutureTask<Ch> task = new FutureTask<Ch>(onlineChopping);
new Thread(task).start();
Thread.sleep(2000);
while (!task.isDone()){
System.out.println("wait");
Thread.sleep(1000);
}
}
}
2.
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Main2 {
public static String work(String name){
System.out.println(name + " starts at " + LocalTime.now());
try {
Thread.sleep(3000);
}catch (Exception e){
}finally {
}
System.out.println(name + " ends at " + LocalTime.now());
return name;
}
private static void useCompleteableFure() throws InterruptedException, ExecutionException {
CompletableFuture<Void> fa = CompletableFuture.runAsync(()->work("a"));
Thread.sleep(1000);
CompletableFuture<Void> fb = CompletableFuture.runAsync(()->work("b"));
System.out.println(fa.get());
System.out.println(fb.get());
}
public static void main(String[] args) throws InterruptedException, ExecutionException{
useCompleteableFure();
}
}