上面就是泡茶的步骤,我们开启两个线程,小王和老王来完成泡茶。
public class TwoThreadPaoTea {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":洗水壶");
sleep(1);
System.out.println(Thread.currentThread().getName() + ":烧开水");
sleep(5);
}, "老王");
Thread t2 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":洗茶壶");
sleep(1);
System.out.println(Thread.currentThread().getName() + ":洗茶杯");
sleep(2);
System.out.println(Thread.currentThread().getName() + ":拿茶叶");
sleep(1);
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":泡茶");
}, "小王");
t1.start();
t2.start();
}
public static void sleep(int i) {
try {
TimeUnit.SECONDS.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
结果
老王:洗水壶
小王:洗茶壶
老王:烧开水
小王:洗茶杯
小王:拿茶叶
小王:泡茶