Java Thread.join怎樣保證線程同步

小樊
81
2024-10-09 15:52:50

Thread.join() 方法在 Java 中用于確保一個(gè)線程在另一個(gè)線程完成執(zhí)行之前不會(huì)繼續(xù)執(zhí)行。這有助于實(shí)現(xiàn)線程同步,確保線程按照預(yù)期的順序執(zhí)行。

當(dāng)你調(diào)用一個(gè)線程的 join() 方法時(shí),當(dāng)前線程會(huì)阻塞,直到被調(diào)用 join() 方法的線程執(zhí)行完畢。這樣可以確保線程按照調(diào)用順序執(zhí)行,從而實(shí)現(xiàn)線程同步。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何使用 Thread.join() 實(shí)現(xiàn)線程同步:

public class JoinExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread 1 is running.");
                try {
                    // 暫停2秒,模擬線程1的執(zhí)行時(shí)間
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1 is finished.");
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread 2 is running.");
                try {
                    // 暫停2秒,模擬線程2的執(zhí)行時(shí)間
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2 is finished.");
            }
        });

        // 確保線程1先執(zhí)行
        thread1.start();
        try {
            // 等待線程1執(zhí)行完畢
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 線程1執(zhí)行完畢后,線程2開始執(zhí)行
        thread2.start();
    }
}

在這個(gè)示例中,我們創(chuàng)建了兩個(gè)線程 thread1thread2。我們使用 thread1.join() 確保 thread1thread2 之前執(zhí)行。這樣,我們可以控制線程的執(zhí)行順序,實(shí)現(xiàn)線程同步。

0