以下是一个例子:

public class SynchronizedExample {

    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }

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

        // create multiple threads
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    example.increment();
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    example.increment();
                }
            }
        });

        // start the threads
        thread1.start();
        thread2.start();

        // wait for the threads to finish
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // print the final count
        System.out.println("Final count: " + example.getCount());
    }
}

这个例子中,我们定义了一个类SynchronizedExample,其中有一个计数器count。我们使用synchronized关键字来定义了两个同步方法increment()getCount(),以确保多个线程不能同时访问这两个方法。

main()方法中,我们创建了两个线程,并分别启动它们。每个线程都会执行1000次increment()方法,以增加计数器的值。

最后,我们等待这两个线程完成,然后打印最终的计数器值。由于这两个线程是同步执行的,所以最终的计数器值应该是2000

请编写一个有同步方法的Java多线程代码

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

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