public class ThreadSafeExample {
    private int j = 0;

    public synchronized void increase() {
        j++;
    }

    public synchronized void decrease() {
        j--;
    }

    public static void main(String[] args) {
        ThreadSafeExample example = new ThreadSafeExample();

        Thread increaseThread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increase();
            }
        });

        Thread increaseThread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increase();
            }
        });

        Thread decreaseThread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.decrease();
            }
        });

        Thread decreaseThread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.decrease();
            }
        });

        increaseThread1.start();
        increaseThread2.start();
        decreaseThread1.start();
        decreaseThread2.start();

        try {
            increaseThread1.join();
            increaseThread2.join();
            decreaseThread1.join();
            decreaseThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("The final value of j is: " + example.j);
    }
}

在上述代码中,我们使用synchronized关键字来保证对共享变量j的访问是同步的。这样可以避免多个线程同时对j进行修改的情况,从而保证了线程安全性

java中设计4个线程其中两个线程每次对j增加1另外两个线程对j每次减少1。考虑到线程的安全性写出程序

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

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