int i++和++i是线程安全的吗?

话不多说,直接贴测试类:

public class ThreadUnSafeDemo {

  //    private AtomicInteger value = new AtomicInteger(1);
  private static int value = 1;
//  private static volatile int value = 1;

  public static void main(String[] args) throws InterruptedException {

    CountDownLatch latch = new CountDownLatch(1);

    for (int i = 0; i < 5; i++) {
      CompletableFuture.runAsync(() -> {
        while (true) {
          System.out.println("正在出票" + (value++) + "");
//            safeMethod();
          if (value > 80) {
            latch.countDown();
          }
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      });
    }
    latch.await();
    System.out.println("执行完毕...");
  }

  public synchronized static void safeMethod() {
    System.out.println("正在出票" + (value++) + "");
  }

}

执行结果:
在这里插入图片描述
结果:不安全,因为i++,++i会在内存中新建个int j = i+1,然后将j赋值给i,当线程在新建了j的时候,cpu进行了切换,这时候i还是等于原来的值,就会导致不安全,以出票举例,卖出了99号票卖出了多张…
解决,方法加synchronized,使用AtomicInteger,也就是使用Atomic包下的类,他的方法是具有原子性的…

世界上所有的不公平都是由于当事人能力不足造成的.
原文地址:https://www.cnblogs.com/javayida/p/13346764.html