天天看點

Thread多線程進行加鎖控制執行順序synchronized加鎖對類的對象進行加鎖保證執行原子性,達到保證順序性的要求

package com.tl.executor.locks;

public class Sync03 implements Runnable {
  static int i = 0;

  @Override
  public void run() {
    for (int j = 0; j < 100000; j++) {
      synchronized (Sync03.class) {
        i++;

      }

    }
    System.out.println(Thread.currentThread().getName() + "||||||||" + i);
  }

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

    Thread thread1 = new Thread(new Sync03());
    Thread thread2 = new Thread(new Sync03());
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    System.out.println(i);

  }

}
/****
 * 執行結果:
Thread-0||||||||160619
Thread-1||||||||200000
200000

 * 
 */