1. 程式人生 > >執行緒同步基礎——lock介面的使用

執行緒同步基礎——lock介面的使用

/**
 * 列印工作類
 * @author Administrator
 *
 */
public class Job implements Runnable {
	private PrintQueue printQueue;

	public Job(PrintQueue printQueue) {
		super();
		this.printQueue = printQueue;
	}

	@Override
	public void run() {
		printQueue.printJob(new Object());
		
	}
	
	/**
	 * 主函式入口
	 * 建立了10個執行緒
	 * @param args
	 */
	public static void main(String[] args) {
		PrintQueue pq = new PrintQueue();
		Thread thread[] = new Thread[10];
		for (int i = 0; i < 10; i++) {
			thread[i] = new Thread(new Job(pq), "Thread"+i);
		}
		
		for (int i = 0; i < 10; i++) {
			thread[i].start();
		}
	}

}

/**
 * 列印佇列 
 * @author Administrator
 *
 */
public class PrintQueue {
	private final Lock queueLock = new ReentrantLock();

	//列印工作
	public void printJob(Object document) {
		//獲取控制權
		queueLock.lock();
		long duration = (long) (Math.random() * 10000);
		System.out.println(Thread.currentThread().getName()+":Test print job ! "+duration);
		try {
			Thread.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			//如果不釋放鎖,會造成死鎖現象
			queueLock.unlock();
		}

	}

}