java - 同步、连接和线程安全
问题描述
我已经阅读了其他示例,但不明白为什么注释掉 t.join() 的这段代码并不总是具有 count 的最终值 5000,但是当代码被注释时,count 总是在末尾是 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;
}
}
解决方案
推荐阅读
- hdfs - oozie 错误:不允许访问本地文件系统
- asp.net - 可访问 HttpContext 的 ASP.NET 任务调度
- strpos - 在 Strpos 中排除多个 url - 为什么它不起作用?
- java - 使用 Spring Boot 从命令行接收输入
- go - 根据另一个切片中元素的顺序对切片进行排序
- python - 从 python 中的 pandas.Series 中删除特殊字符?
- javascript - 如何使用 Json 对象填充动态添加的输入字段
- android - 如何在 firebase 数据库中找到特定值并获取有关该值的所有信息?将驱动程序与客户问题匹配?
- java - Spring Boot、MySQL、Tomcat 无法在 Eclipse 中创建池的初始连接
- shell - 比较一个文件的两列和另一个文件的两列