所谓线程安全就是指由于线程之间的抢占式执行,线程操作的非原子性导致最终的结果与预期的结果不一致的情况
class Counter{
public static int count = 0;
public synchronized void increase(){ //枷锁
count++;
}
}
public class TestDemo {
private static Counter counter= new Counter();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 50000; i++) {
counter.increase();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 50000; i++) {
counter.increase();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("counter: " + counter.count);
}
}
通过上诉代码,用t1和t2同时进行count++的操作,其理论结果应该是10000,但是实际上的结果是小于10000的,这就表明出现了线程安全的问题为什么会出现上述的线程安全的问题下面我通过一个例子进行讲解