烧水泡茶问题
Future类和普通线程
Future相对于普通线程的区别是可以把线程执行的结果传给调用者
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test3 {
private static final Callable callable1 = () -> {
Thread.sleep(3000L); // 模拟烧水动作
System.out.println("烧开水成功");
return "hot_water";
};
private static final FutureTask ft1 = new FutureTask<>(callable1);
private static final Callable callable2 = () -> {
if(ft1.get().equals("hot_water")){
Thread.sleep(1000L); // 模拟泡茶动作
System.out.println("泡茶成功");
return "tea is done";
}else{
return "tea is not done";
}
};
private static final FutureTask ft2 = new FutureTask<>(callable2);
public static void main(String[] args) throws Exception {
long l = System.currentTimeMillis();
//Future类
// Thread thread1 = new Thread(ft1);
// Thread thread2 = new Thread(ft2);
// thread1.start();
// ft1.get();thread1.join();
// thread2.start();
// thread2.join();
// ft2.get();
//常规线程
Thread t1 = new HotWaterThread();
Thread t2 = new TeaThread();
t1.start();
t1.join();
t2.start();
t2.join();
System.out.println("结束:"+(System.currentTimeMillis() - l)/1000);
}
private static volatile boolean hot_water = false;
private static class HotWaterThread extends Thread{
@Override
public void run() {
try{
Thread.sleep(3000L);
hot_water = true;
System.out.println("水已经烧开");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
private static class TeaThread extends Thread{
@Override
public void run() {
try{
if(hot_water){
Thread.sleep(1000L);
System.out.println("茶泡好了");
}else{
System.out.println("没有热水");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}



