title: Why does this method lead to concurrency issues?
body: <p>I synchronize the code below, but it leads to concurrency issues.</p>
  
  <p>I know this is caused by multi-thread, I was confused by the <code>synchronized</code> keyword. I expected a <code>list.length</code> value of 100. How can I fix it?</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.Date;
  import java.util.List;
  
  public class ThreadA extends Thread {
  
      private static byte[] lock = new byte[0];
  
      private static final List&lt;String&gt; list = new ArrayList&lt;String&gt;();
  
      @Override
      public void run() {
  
          System.out.println(list.size());
  
          synchronized(lock) {
              int size = list.size();
              if( size == 0 ) return;
  
              if(size &gt;= 100) {
                  list.clear();
              }
          }
  
      }
  
      public void add(String s) {
          list.add(s);
      }
  
      public static void main(String[] args) {
  
          for(int i = 0; i &lt; 100; i++) {
              new ThreadA().start();
              new Thread(new Runnable() {
  
                  @Override
                  public void run() {
                      synchronized(lock) {
                          for(int m = 0; m &lt; 100; m++) {
                              list.add(new Date().toLocaleString());
                          }
                      }
                  }
              }).start();
          }
  
          System.out.println("LIST.SIZE:" + list.size());
      }
  
  }
  </code></pre>