泡茶的逻辑
在讲到并行时,有些资料中会提到关于泡茶的例子——也就是有两种泡茶方式。
可以看到,这两种方式消耗的时间是不同的。
完全可以在烧开水的同时去做其他的准备工作,例如,洗茶杯、准备茶叶等,把烧开水和其他准备事项并行起来做,可以大大节约总的耗时时间。
先用代码来展示第一种串行的泡茶方式
。
/**
* 烧开水
*
*/
public class BoilWater {
private boolean status = false;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
/**
* 其他准备工作
*
*/
public class OtherPreparation {
private boolean status = false;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
/**
* 串行的泡茶步骤
*
*/
public class SerialMakeTea {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread t1 = new Thread(() -> {
System.out.println("烧水开始:需要5分钟");
try {
BoilWater bw = new BoilWater();
bw.setStatus(true);
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("烧水结束");
});
t1.start();
t1.join();
Thread t2 = new Thread(() -> {
System.out.println("其他准备开始:需要2分钟");
try {
OtherPreparation tc = new OtherPreparation();
tc.setStatus(true);
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("其他准备结束");
});
t2.start();
t2.join();
System.out.println("总共耗时:" + (System.currentTimeMillis() - start) / 1000 + " 分钟");
}
}
原创大约 2 分钟