小编use*_*362的帖子

可重入锁无法正确更新共享资源

我有一个共享变量计数,我在方法中递增它increment(),并且两个线程正在访问它。我得到了错误的最终计数。这是代码片段:

public class ReentrantLockTest {
    static volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 10000; i++){
                    increment();
                }
            }
        });


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 10000; i++){
                    increment();
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println("Counter variable : "+count);

    }
    private static …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading

1
推荐指数
1
解决办法
129
查看次数

标签 统计

concurrency ×1

java ×1

multithreading ×1