1. 程式人生 > >Java多執行緒同步之Lock用法

Java多執行緒同步之Lock用法

從JDK5.0開始,有兩種機制來保護程式碼塊不受到並行訪問的干擾。舊版本的Java使用synchronized關鍵字來達到這個目的,而JDK5.0引進了ReentrantLock()類。synchronize關鍵字自動提供一個鎖和相關的條件。
用ReentrantLock保護程式碼塊的結構如下:
Lock myLock = new ReentrantLock();

myLock.lock()
try{
    需要保護的程式碼塊;
    }
finally{
    myLock.unlock
    }

下面是用法示例:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class WorkThread extends Thread{
    private
CourruptedData data = null ; private int type = 0 ; public WorkThread(CourruptedData _data,int _type){ data = _data ; type = _type ;//快程序和滿程序的標記。 super.start(); } public void run(){ data.performWork(type); } } public class CourruptedData { protected
static int display = 1 ; protected static int change = 2 ; private WorkThread slowWorker = null ; private WorkThread fastWorker = null ; private int number = 0 ; private volatile double f = 1.1; Lock lock = new ReentrantLock(); public CourruptedData() { number = 1
; slowWorker = new WorkThread(this,display);//-----------慢程序先啟動; fastWorker = new WorkThread(this,change); } /* * 關鍵字為synchronized時,方法修飾為同步方法, * 慢執行緒呼叫performWokr()時,休眠兩秒; * 此時,不允許第二個執行緒打斷第一個執行緒; * 等第一個執行緒執行完畢之後,第二個執行緒才能將number改為-1; */ public void performWork(int type){ if (type == display) { lock.lock(); try{ System.out.println("Number before sleeping:" + number); try{ slowWorker.sleep(2000); }catch (InterruptedException ie){ System.out.println("Error : "+ie); } System.out.println("Number after working up:"+ number); } finally{ lock.unlock(); } } if (type == change) { lock.lock(); try{ System.out.println("Change the numbering:"); number = -1 ; System.out.println(number); } finally{ lock.unlock(); } } } public static void main(String args[]) { CourruptedData test = new CourruptedData(); } }