繁体   English   中英

如何通过扩展线程 class 来同步 Java 中的两个线程?

[英]How can I synchronize two threads in Java by extending the Thread class?

我正在学习 Java 中的同步,但我不知道为什么我不能得到 24000 作为“c.count”的结果。 当我运行代码时,我得到 23674、23853 等。你知道为什么吗?

public class Counter {
    public int count = 0;

    public static void main(String[] args) throws InterruptedException {
        
        Counter c = new Counter();
        
        ThreadT t1 = new ThreadT(c);
        ThreadT t2 = new ThreadT(c);        
        
        t1.start();
        t2.start();
        
        t1.join();
        t2.join();
        System.out.println(c.count);

    }
}

class ThreadT extends Thread {
    Counter c;

    ThreadT(Counter c) {
        this.c = c;
    }
    public void run() {
        for (int i = 0; i < 12000; i++) {
            add();
        }
    }

    synchronized void  add() {
    c.count++;
    }
}```

请注意, t1调用在t1 object 上add ,而t2调用在t2 object 上add 虽然add是同步的,但t1t2是两个不同的对象,因此两个线程彼此不同步。

每个线程在自己的线程object上调用一个同步方法,所以它只与自己同步。 您需要两个线程在同一个 object 上调用同步方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM