java - 多线程和锁

标签 java multithreading

在进入条件之前,我试图了解锁和多线程的工作原理。这是我目前正在测试的代码:

public class tester {
    private static int count = 0;

    public void incrementCount() {
        count++;
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new testing());
        Thread thread2 = new Thread(new testing());
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(count);
    }
}

这是实现 Runnable 的部分:

public class testing implements Runnable {
    Lock lock = new ReentrantLock();
    tester in = new tester();

    public void run() {
        for (int i = 0; i < 1000; i++) {
            lock.lock();
            in.incrementCount();
            lock.unlock();

        }
    }
}

我遇到的问题是,我试图在 main 方法的末尾打印出 2000,但即使我使用了锁,它也从未真正达到 2000。帮助将不胜感激!

最佳答案

even though I am using locks.

您正在为两个线程中的每一个使用单独的锁。

如果你想让锁在线程之间协调,它们都需要使用同一个锁实例。否则毫无意义。

改成类似的东西

class Testing implements Runnable {
    private final Lock lock;

    // pass in the lock to use via the constructor
    // both threads need to receive the same lock
    Testing(Lock lock){ this.lock = lock; }           

    public void run() {
        for (int i = 0; i < 1000; i++) {
            lock.lock();
            Tester.incrementCount();
            lock.unlock();
        }
    }
}

关于java - 多线程和锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096660/

相关文章:

java - 通过 Oracle SQL Developer 工具加载 Java 文件

c - 为什么 pthread_cond_signal 不起作用?

java - 多线程更新表面 View Canvas

ios - 发送 NSNotification 时,CustomCell 中的 UIProgressView 从不显示

java - 查询有关简单线程示例的输出

java - 循环语句后未调用代码

java - 从网页簇中提取最佳图像

java - 与最新版本 Selenium Webdriver 和 PhantomJs 的兼容性问题

java - 如何从 Java 中格式错误的字符串中获取属性和值

Java:如何使用 synchronized 和 volatile