首页 > 代码库 > Java并发学习之十四——使用Lock同步代码块

Java并发学习之十四——使用Lock同步代码块

本文是学习网络上的文章时的总结,感谢大家无私的分享。

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();
		}
	}

}


Java并发学习之十四——使用Lock同步代码块