synchronized(一般对象)
一次只有一个线程进入该代码块.此时,线程获得的是成员锁.例如:
1 public class Thread7 { 2 private Object xlock = new Object(); 3 4 public void sync_fun() { 5 // synchronized (a1) {//synchronized只能是对象,基本类型不可以. 6 synchronized (xlock) { 7 int i = 5; 8 while (i-- > 0) { 9 System.out 10 .println(Thread.currentThread().getName() + " : " + i); 11 try { 12 Thread.sleep(500); 13 } catch (InterruptedException ie) { 14 } 15 } 16 } 17 } 18 public void no_sync_fun() { 19 int i = 5; 20 while (i-- > 0) { 21 System.out.println(Thread.currentThread().getName() + " : " + i); 22 try { 23 Thread.sleep(500); 24 } catch (InterruptedException ie) { 25 } 26 } 27 } 28 public static void main(String[] args) { 29 final Thread7 t7 = new Thread7(); 30 Thread t1 = new Thread(new Runnable() { 31 @Override 32 public void run() { 33 t7.sync_fun(); 34 } 35 }, "t1"); 36 Thread t2 = new Thread(new Runnable() { 37 @Override 38 public void run() { 39 t7.sync_fun(); 40 } 41 }, "t2"); 42 Thread t3 = new Thread(new Runnable() { 43 @Override 44 public void run() { 45 t7.sync_fun(); 46 } 47 }, "t3"); 48 Thread t4 = new Thread(new Runnable() { 49 @Override 50 public void run() { 51 t7.sync_fun(); 52 } 53 }, "t4"); 54 Thread no_sync = new Thread(new Runnable() { 55 @Override 56 public void run() { 57 t7.no_sync_fun(); 58 } 59 }, "no_sync"); 60 t1.start(); 61 t2.start(); 62 no_sync.start(); 63 t3.start(); 64 t4.start(); 65 } 66 }
结果:
t1 : 4
no_sync : 4
t1 : 3
no_sync : 3
t1 : 2
no_sync : 2
t1 : 1
no_sync : 1
t1 : 0
no_sync : 0
t4 : 4
t4 : 3
t4 : 2
t4 : 1
t4 : 0
t3 : 4
t3 : 3
t3 : 2
t3 : 1
t3 : 0
t2 : 4
t2 : 3
t2 : 2
t2 : 1
t2 : 0