同步、连接和线程安全

时间:2021-05-12 08:10:55

标签: java thread-safety

我已经阅读了其他示例,但不明白为什么注释掉 t.join() 的这段代码并不总是具有计数的结束值 5000,但是当代码被注释时,计数总是在 5000 处结束。但为什么?我认为静态锁对象一次只能由一个线程拥有,当拥有它时,其他线程必须等到它被释放。所以我不明白为什么 join() 是必要的以及到底发生了什么。

import java.util.ArrayList;

public class MyClass implements Runnable {
    private static int count = 0;
    private static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 1; i <= 5000; i++)
            threads.add(new Thread(new MyClass()));

        for (Thread t : threads)
            t.start();
        // for (Thread t : threads)
        //     t.join();

        System.out.println("Total count = " + MyClass.getCount());
    }

    public void run() {
        synchronized (lock) {
            count++;
        }
    }

    public static int getCount() {
        return count;
    }
}

0 个答案:

没有答案
相关问题