Java併發學習之十四——使用Lock同步程式碼塊
阿新 • • 發佈:2019-01-08
本文是學習網路上的文章時的總結,感謝大家無私的分享。
Java提供另外的機制用來同步程式碼塊。它比synchronized關鍵字更加強大、靈活。Lock
介面比synchronized關鍵字提供更多額外的功能。在使用Lock時需要注意的是要釋放Lock鎖。
package chapter2; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * 列印佇列 */ public class PrintQueue { private final Lock queueLock = new ReentrantLock(); public void printJob(Object document){ queueLock.lock();//獲取Lock物件的控制權 try { Long duration = (long)(Math.random()*10000); System.out.println(Thread.currentThread().getName() +"PrintQueue:Printing a Job during " +(duration/1000)+" seconds"); Thread.sleep(duration); } catch (Exception e) { e.printStackTrace(); } finally{ queueLock.unlock();//釋放Lock物件的控制 } } }
package chapter2; public class Job implements Runnable{ private PrintQueue printQueue; public Job(PrintQueue printQueue){ this.printQueue = printQueue; } @Override public void run() { System.out.printf("%s:Going to print a document\n", Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s:The document has been printed\n",Thread.currentThread().getName()); } }
package chapter2; /** * * <p> * Description: 使用Lock同步程式碼塊 * </p> * @author zhangjunshuai * @version 1.0 * Create Date: 2014-9-16 下午4:57:06 * Project Name: Java7Thread * * <pre> * Modification History: * Date Author Version Description * ----------------------------------------------------------------------------------------------------------- * LastChange: $Date:: $ $Author: $ $Rev: $ * </pre> * */ public class Main5 { /** * <p> * </p> * @author zhangjunshuai * @date 2014-9-16 下午4:57:00 * @param args */ public static void main(String[] args) { PrintQueue printQueue = new PrintQueue(); Thread thread[] = new Thread[10]; for(int i=0;i<10;i++){ thread[i] = new Thread(new Job(printQueue),"Thread"+i); } for(int i=0;i<10;i++){ thread[i].start(); } } }