我已经开始学习线程中的同步我写了一些代码为什么有时同步块不能正常工作?

nr9pn0ug  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(278)

我只是想用两个线程来增加变量,但有时会显示值不正确。

public class SynchBlock {
public static void main(String[] args) throws InterruptedException {
        SynchBlock obj= new SynchBlock();
        obj.dowork();
}
    }

同步块法

private int count;
    public void call() {
        synchronized (this) {
            count++;
        }
    }

synchblock运行线程的方法

public void dowork() throws InterruptedException {
        th1.start();
        th2.start();
        th1.join();
        th1.join();
        System.out.println(count);
    }

线程类1只是增加了count的值

Thread th1 = new Thread(new Runnable() {

        public void run() {
            for (int i = 0; i < 10000; i++) {
                call();
            }
        }

    });

线程类2只是增加了count的值

Thread th2 = new Thread(new Runnable() {

        public void run() {
            for (int i = 0; i < 10000; i++) {
                call();
            }
        }

    });
j8yoct9x

j8yoct9x1#

你不加入 th2 . 你加入 th1 两次,所以有时你打印 count 之前 th2 完成了。

相关问题