Java Thread.join在哪里可以使用同步輔助類

小樊
81
2024-10-09 14:39:50

Thread.join() 方法用于等待線程執(zhí)行完成。在使用 Thread.join() 時(shí),為了確保線程安全,可以使用同步輔助類,如 synchronized 關(guān)鍵字、Lock 接口或 ReentrantLock 類等。

以下是一些使用同步輔助類的示例:

  1. 使用 synchronized 關(guān)鍵字:
class MyRunnable implements Runnable {
    @Override
    public void run() {
        synchronized (lock) {
            // 臨界區(qū)代碼
        }
    }
}

public class Main {
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        thread1.start();
        thread2.start();

        thread1.join(); // 等待 thread1 執(zhí)行完成
        thread2.join(); // 等待 thread2 執(zhí)行完成
    }
}
  1. 使用 Lock 接口:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyRunnable implements Runnable {
    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        lock.lock(); // 獲取鎖
        try {
            // 臨界區(qū)代碼
        } finally {
            lock.unlock(); // 釋放鎖
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        thread1.start();
        thread2.start();

        thread1.join(); // 等待 thread1 執(zhí)行完成
        thread2.join(); // 等待 thread2 執(zhí)行完成
    }
}
  1. 使用 ReentrantLock 類:
import java.util.concurrent.locks.ReentrantLock;

class MyRunnable implements Runnable {
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        lock.lock(); // 獲取鎖
        try {
            // 臨界區(qū)代碼
        } finally {
            lock.unlock(); // 釋放鎖
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        thread1.start();
        thread2.start();

        thread1.join(); // 等待 thread1 執(zhí)行完成
        thread2.join(); // 等待 thread2 執(zhí)行完成
    }
}

在這些示例中,我們使用了不同的同步輔助類來確保在多線程環(huán)境下對(duì)共享資源的訪問是線程安全的。

0