Java多線程基礎(三)Java傳統線程互斥技術,多線程互斥
Java多線程基礎(三)Java傳統線程互斥技術
java的線程互斥主要通過synchronized關鍵字實現。下面的範例程式碼展示了幾種使用synchronized關鍵字的基本用法。
package cn.king;public class TraditionalThreadSynchronized { public static void main(String[] args) { new TraditionalThreadSynchronized().foo(); } private void foo() { // printer須是final的,否則無法編譯。這主要是為了保證printer的一致性。 final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while(true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } /* * Cannot refer to a non-final variable printer * inside an inner class defined in a different method * 更多內容可參閱java8 lambda運算式(閉包)相關知識 */ printer.output("123456789"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } printer.output("abcdefghi"); } } }).start(); } static class Printer { String _lock = ""; public void output(String name) { int len = name.length(); // 同步代碼塊 /* 方法1: * 以this作為鎖對象, * 與使用this加鎖的代碼塊或synchronized方法互斥 */ // synchronized(this) { /* 方法2: * 以Outputer類的位元組碼對象(該對象由虛擬機器自動建立)作為鎖對象, * 與使用Outputer.class加鎖的代碼塊或static synchronized方法互斥 */ // synchronized(Outputer.class) { /* 方法3: * 以自訂對象作為鎖對象, * 與使用_lock加鎖的代碼塊互斥 */ synchronized(_lock) { for(int i=0; i<len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } } // 同步方法,相當於synchronized(this){} public synchronized void output2(String name) { int len = name.length(); for(int i=0; i<len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } // 靜態同步方法,相當於synchronized(Outputer.class){} public static synchronized void output3(String name) { int len = name.length(); for(int i=0; i<len; i++) { System.out.print(name.charAt(i)); } System.out.println(); } }}
上面的代碼中展示了三種基本的線程互斥實現。下面詳述三種方法的實現特點和適用情況。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。