什么是线程安全?
无论遇到怎么样的多个线程访问某对象或某方法的情况,不需要额外做任何的处理。程序也可以正常的运行,不会有因为多线程而出错,因此称为线程安全。
线程不安全:get同时set、额外同步。
全都线程安全? 运行速度、设计成本、tradeoff
什么时候会出现线程安全问题?
第一个线程安全问题:
a++问题。在多线程操作a++,并且将其打印时,我们会发现其会出现少+的情况。通过for循环控制run的次数,再利用原子化变量与常规变量的区别,探究何时少+的情况,并且能够找到,少+的位置。
package MutiThreadSafe; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; /** * @program:多线程和IO * @descripton: * @author:ZhengCheng * @create:2021/9/23-15:29 **/ public class ErrorCountNums implements Runnable{ private static int a = 0; private static boolean[] marked = new boolean[2000001]; private static AtomicInteger realIndex = new AtomicInteger(); private static AtomicInteger wrongTimes = new AtomicInteger(); private static CyclicBarrier cb1 = new CyclicBarrier(2); private static CyclicBarrier cb2 = new CyclicBarrier(2); public static void main(String[] args) throws InterruptedException { ErrorCountNums ern = new ErrorCountNums(); Thread thread1 = new Thread(ern); Thread thread2 = new Thread(ern); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System