Java中一個物件在多執行緒中是共享的

weixin_34007886發表於2018-06-07
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之後,先執行加再減,但是輸出的是把執行減的操作列印出來後再列印加的操作結果,所以,對於多執行緒中的資料操作是會引發併發衝突的,

相關文章