Java中一个对象在多线程中是共享的

public class begin {
  public static void main(String[] arg) {
    Data data = new Data(0);
    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        data.path = data.path + "+";
        System.out.println("increment, value = " + String.valueOf(data.increment()) + ", " + data.path);
      }
    }).start();

    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        data.path = data.path + "-";
        System.out.println("decrement, value = " + String.valueOf(data.decrement()) + ", " + data.path);
      }
    }).start();
  }

  static class Data {
    int value;
    String path;

    Data(int i) {
      value = i;
      path = "";
    }

    int increment() {
      return ++value;
    }

    int decrement() {
      return --value;
    }
  }
}

输出打印:

increment, value = 1, +
increment, value = 2, ++
increment, value = 3, +++
decrement, value = 2, +++-
decrement, value = 2, +++-+-
increment, value = 3, +++-+
increment, value = 2, +++-+--+
increment, value = 3, +++-+--++
increment, value = 4, +++-+--+++
increment, value = 5, +++-+--++++
increment, value = 6, +++-+--+++++
increment, value = 7, +++-+--++++++
decrement, value = 1, +++-+--
decrement, value = 6, +++-+--++++++-
decrement, value = 5, +++-+--++++++--
decrement, value = 4, +++-+--++++++---
decrement, value = 3, +++-+--++++++----
decrement, value = 2, +++-+--++++++-----
decrement, value = 1, +++-+--++++++------
decrement, value = 0, +++-+--++++++-------

注意:输出的日志可以看出,执行加操作的线程后,会在某一时刻执行减操作,而且多线程中“打印”这个行为也是有可能滞后的,如第二次 value = 2之后,先执行加再减,但是输出的是把执行减的操作打印出来后再打印加的操作结果,所以,对于多线程中的数据操作是会引发并发冲突的,

你可能感兴趣的:(Java中一个对象在多线程中是共享的)