1. 程式人生 > >Java多線程synchronized關鍵字

Java多線程synchronized關鍵字

print static sync log nbsp 關鍵字 public true current

synchronized關鍵字代表著同步的意思,在Java中被synchronized修飾的有三種情況

1.同步代碼塊

//鎖為obj
synchronized(obj){ while(true){ if(product > 0){ System.out.println(Thread.currentThread().getName()+"消費:"+product--); } } }

2.同步函數

//鎖為this
public synchronized void consume() { while(true){ if(product > 0){ System.out.println(Thread.currentThread().getName()+"消費:"+product--); } } }

  

3.靜態同步函數

//鎖為this.getClass()
static public synchronized void consume() { while(true){ if(product > 0){ System.out.println(Thread.currentThread().getName()+"消費:"+product--); } } }

  

Java多線程synchronized關鍵字