image.png
    上面就是泡茶的步骤,我们开启两个线程,小王和老王来完成泡茶。

    1. public class TwoThreadPaoTea {
    2. public static void main(String[] args) {
    3. Thread t1 = new Thread(() -> {
    4. System.out.println(Thread.currentThread().getName() + ":洗水壶");
    5. sleep(1);
    6. System.out.println(Thread.currentThread().getName() + ":烧开水");
    7. sleep(5);
    8. }, "老王");
    9. Thread t2 = new Thread(() -> {
    10. System.out.println(Thread.currentThread().getName() + ":洗茶壶");
    11. sleep(1);
    12. System.out.println(Thread.currentThread().getName() + ":洗茶杯");
    13. sleep(2);
    14. System.out.println(Thread.currentThread().getName() + ":拿茶叶");
    15. sleep(1);
    16. try {
    17. t1.join();
    18. } catch (InterruptedException e) {
    19. e.printStackTrace();
    20. }
    21. System.out.println(Thread.currentThread().getName() + ":泡茶");
    22. }, "小王");
    23. t1.start();
    24. t2.start();
    25. }
    26. public static void sleep(int i) {
    27. try {
    28. TimeUnit.SECONDS.sleep(i);
    29. } catch (InterruptedException e) {
    30. e.printStackTrace();
    31. }
    32. }
    33. }

    结果

    1. 老王:洗水壶
    2. 小王:洗茶壶
    3. 老王:烧开水
    4. 小王:洗茶杯
    5. 小王:拿茶叶
    6. 小王:泡茶