Java並發之synchronized
阿新 • • 發佈:2018-04-07
synchronizedsynchronized關鍵字最主要有以下3種應用方式
修飾實例方法,作用於當前實例加鎖,進入同步代碼前要獲得當前實例的鎖;實例鎖,一個實例一把鎖
修飾靜態方法,作用於當前類對象加鎖,進入同步代碼前要獲得當前類對象的鎖;對象鎖,一個對象一把鎖
修飾代碼塊,指定加鎖對象,對給定對象加鎖,進入同步代碼庫前要獲得給定對象的鎖;對象鎖,一個對象一把鎖
實例鎖 public class SuperHakceTest implements Runnable{ public static Integer flag = 0; public synchronized void instanse(){ flag ++; } @Override public void run() { for(int i = 0;i < 1000;i ++){ instanse(); } } public static void main(String[] args) throws Exception{ SuperHakceTest superHakceTest = new SuperHakceTest(); Thread thread1 = new Thread(superHakceTest); Thread thread2 = new Thread(superHakceTest); Thread thread3 = new Thread(superHakceTest); thread1.start();thread2.start();thread3.start(); thread1.join();thread2.join();thread3.join(); System.out.println("LAST FLAG = " + SuperHakceTest.flag); } } 對象鎖 public class SuperHakceTest implements Runnable{ public static Integer flag = 0; public static synchronized void instanse(){ flag ++; } @Override public void run() { for(int i = 0;i < 1000;i ++){ instanse(); } } public static void main(String[] args) throws Exception{ SuperHakceTest superHakceTest1 = new SuperHakceTest(); SuperHakceTest superHakceTest2 = new SuperHakceTest(); SuperHakceTest superHakceTest3 = new SuperHakceTest(); Thread thread1 = new Thread(superHakceTest1); Thread thread2 = new Thread(superHakceTest2); Thread thread3 = new Thread(superHakceTest3); thread1.start();thread2.start();thread3.start(); thread1.join();thread2.join();thread3.join(); System.out.println("LAST FLAG = " + SuperHakceTest.flag); } } //this,當前實例對象鎖 synchronized(this){ for(int j=0;j<1000000;j++){ i++; } } //class對象鎖 synchronized(AccountingSync.class){ for(int j=0;j<1000000;j++){ i++; } }
Java並發之synchronized