|
目录
线程安全问题
1. 线程安全的概念
如果多线程环境下代码运行的结果是符合我们预期的,即在单线程环境应该的结果,则说这个程序是线程安全的。
2. 一个线程不安全示例
class Counter {
public int count = 0;
public Object locker = new Object();
public void increase() {
count++;
}
}
public class Test {
private static Counter counter = new Counter();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 50000;