執行緒同步方法

辉辉、發表於2024-08-15
1.synchronized
2.ReentrantLock(可重入鎖)
public class Main {
    ReentrantLock lock = new ReentrantLock();
    private ThreadLocal stream = new ThreadLocal();

    public static void main(String[] args) {
//        test();
    }

    public void test() {

        lock.lock();

        lock.unlock();
    }
}

3.Semaphore

public class Main {
    static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) throws InterruptedException {
        try {
            semaphore.acquire();
            //執行訪問邏輯
        } finally {
            semaphore.release();
        }
    }
}

相關文章