简体   繁体   English

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

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

I am learning synchronization in Java and I cant find out why I cant get 24000 as a result for "c.count".我正在学习 Java 中的同步,但我不知道为什么我不能得到 24000 作为“c.count”的结果。 When I run the code I get 23674, 23853, etc. Do you have any idea why?当我运行代码时,我得到 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++;
    }
}```

Notice that t1 calls add on the t1 object while t2 calls add on the t2 object.请注意, t1调用在t1 object 上add ,而t2调用在t2 object 上add While add is synchronized, t1 and t2 are two different objects, so the two threads are not synchronizing with each other .虽然add是同步的,但t1t2是两个不同的对象,因此两个线程彼此不同步。

Each thread calls a synchronized method on its own thread object, so it synchronizes only with itself.每个线程在自己的线程object上调用一个同步方法,所以它只与自己同步。 You need both threads to call synchronized methods on the same object.您需要两个线程在同一个 object 上调用同步方法。

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

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