public class SynchronizedDEmo { public static void main(String[] args) { TestThread tt = new TestThread(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); } } class TestThread implements Runnable{ private static int num = 0; public void run() { synchronized(this){ //此處this指的是進入此代碼塊的線程對象,如果t1進來了,那么鎖住t1,若t1時間片結束了,
t2走到此處也只能在上一句代碼處等待t1獲得了時間片后執行完synchronized鎖住的所有代碼,
t2才能進去執行,若去掉synchronized(this),則t1和t2隨時都可以進來執行此段代碼中的任何一步,
時間到了另一個接着進來執行 for( int i = 0; i < 20 ; i++){ num ++ ; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + num); } } } }