下面是一个示例程序,使用了synchronized关键字来确保对共享变量j的访问是线程安全的。

public class ThreadExample {
    private static int j = 0;

    public static void main(String[] args) {
        IncrementThread incrementThread1 = new IncrementThread();
        IncrementThread incrementThread2 = new IncrementThread();
        DecrementThread decrementThread1 = new DecrementThread();
        DecrementThread 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 {
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synchronized (ThreadExample.class) {
                    j++;
                }
            }
        }
    }

    static class DecrementThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synchronized (ThreadExample.class) {
                    j--;
                }
            }
        }
    }
}

在上面的示例中,定义了一个静态变量j作为共享变量。然后创建了两个增加j的线程IncrementThread和两个减少j的线程DecrementThread。在每个线程的run方法中,通过synchronized关键字来确保对j的操作是原子的,即同一时间只有一个线程能够访问j,并防止竞态条件的发生。

在main方法中,启动了四个线程,并使用join方法等待所有线程执行完毕。最后打印出最终的j的值。

注意:虽然使用synchronized关键字确保了线程安全,但是在多线程环境中,增加j和减少j的操作可能会交替执行,因此最终的结果可能不是预期的20000。如果需要确保每个线程的操作都执行完后再进行下一轮操作,可以使用CountDownLatch或者CyclicBarrier等同步工具

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

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

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