本示例演示如何使用 Java 中的 ReentrantLock 来确保多个线程对共享变量的访问安全。

程序创建了四个线程,其中两个是 IncrementThread,另外两个是 DecrementThread。每个线程都会对共享变量 j 进行操作,增加或减少 1。为了确保线程安全性,我们使用了 ReentrantLock 来实现互斥访问。在每个线程的 run 方法中,我们首先获取锁,然后对 j 进行操作,最后释放锁。这样可以确保每次只有一个线程能够访问 j,从而避免了竞态条件的发生。

import java.util.concurrent.locks.ReentrantLock;

public class ThreadExample {
    private static int j = 0;
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread incrementThread1 = new IncrementThread();
        Thread incrementThread2 = new IncrementThread();
        Thread decrementThread1 = new DecrementThread();
        Thread decrementThread2 = new DecrementThread();

        incrementThread1.start();
        incrementThread2.start();
        decrementThread1.start();
        decrementThread2.start();

        try {
            incrementThread1.join();
            incrementThread2.join();
            decrementThread1.join();
            decrementThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println('Final value of j: ' + j);
    }

    static class IncrementThread extends Thread {
        public void run() {
            for (int i = 0; i < 100000; i++) {
                lock.lock();
                try {
                    j++;
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class DecrementThread extends Thread {
        public void run() {
            for (int i = 0; i < 100000; i++) {
                lock.lock();
                try {
                    j--;
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}

在 main 方法中,我们启动了四个线程,并使用 join 方法等待它们全部执行完毕。最后,我们输出 j 的最终值,以验证程序的正确性。


原文地址: https://www.cveoy.top/t/topic/pvmg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录