title: How to synchronized one method when parallelStream call in Java?
body: <p>I want to Synchronize functionB. I mean, when some Attriute object call functionA, there are always just run one of object's functionB in the same time. But functionC and functionD in each object can do it after functionB finished by themselves.</p>
  <p>I tried to add synchronized in function B, but it seems like not work.</p>
  <p>This is Attribute class:</p>
  <pre><code>public class Attribute {
      private String name;
  
      Attribute(String name) {
          this.name = name;
      }
  
      public void functionA() {
          synchronized (this) {
              functionB();
          }
          functionC();
          functionD();
      }
  
      private void functionB() {
          for (int i = 0; i &lt; 5; i++) {
              System.out.println(name + &quot; &quot; + i + &quot; time functionB.&quot;);
          }
      }
  
      private void functionC() {
          for (int i = 0; i &lt; 5; i++) {
              System.out.println(name + &quot; &quot; + i + &quot; time functionC.&quot;);
          }
      }
  
      private void functionD() {
          for (int i = 0; i &lt; 5; i++) {
              System.out.println(name + &quot; &quot; + i + &quot; time functionD.&quot;);
          }
      }
      
      public static void main(String[] args) throws IOException {    
          ArrayList&lt;Attribute&gt; attributes = new ArrayList&lt;&gt;();
          for (int i = 0; i &lt; 5; i++) {
               attributes.add(new Attribute(&quot;No.&quot; + i));
          }
          attributes.parallelStream().forEach(Attribute::functionA);
      }
  }
  </code></pre>
  <p>After execute above code, the console show:</p>
  <pre><code>No.3 0 time functionB.
  No.4 0 time functionB.
  No.2 0 time functionB.
  No.2 1 time functionB.
  No.2 2 time functionB.
  No.1 0 time functionB.
  No.1 1 time functionB.
  ...
  </code></pre>
  <p>But I expect it:</p>
  <pre><code>No.3 0 time functionB.
  No.3 1 time functionB.
  No.3 2 time functionB.
  No.3 3 time functionB.
  No.3 4 time functionB.
  No.1 0 time functionB.
  No.1 1 time functionB.
  No.1 2 time functionB.
  No.1 3 time functionB.
  No.1 4 time functionB.
  No.4 0 time functionB.
  No.4 1 time functionB.
  ...
  No.1 1 time functionD.
  No.3 3 time functionC.
  No.2 3 time functionD.
  No.1 2 time functionD.
  No.4 2 time functionC.
  </code></pre>