首页 > 编程语言 > 详细

Java多线程之~~~Lock接口和ReentrantLock的使用

时间:2014-09-19 23:59:06      阅读:642      评论:0      收藏:0      [点我收藏+]

在多线程开发中,除了synchronized这个关键字外,我们还能通过Lock接口来实现这种效果。通过Lock接口来实现

这种多线程加锁效果的好处是非常的灵活,我们不在需要对整个函数加锁,而且可以很方便的把他放在我们函数的任何

一个地方,非常的称心,而且从效率上来说,使用Lock接口要比使用synchronized关键字效率高一些,下面我们来使用

一个例子来说明这种方法的使用。


package com.bird.concursey.charpet3;

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 com.bird.concursey.charpet3;

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();
		Long duration=(long)(Math.random() * 10000);
		System.out.println(Thread.currentThread().getName()+ ":PrintQueue: Printing a Job during "+(duration/1000)+" seconds");
		try {
			Thread.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			queueLock.unlock();
		}
	}
	
	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接口和ReentrantLock的使用

原文:http://blog.csdn.net/a352193394/article/details/39404247

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!