ITeye博客

并发笔记-----------使用显示的Lock对象

ren2881971 · 2012-08-01 17:18 · java · 多线程 · 编程语言 · Lock · Synchronized · concurrent · Markdown

java机制中除了用synchronized关键字来做同步一外。 还可以用java.util.concurrent.lock包中的类 Lock lock=new ReentrantLock()来代替synchronized同步锁 区别是: 使用synchronized 失败会抛出异常。 而使用Lock后可以finally{}讲系统维护在正确的状态 Lock对象必须被显示的创建,锁定和释放。 虽然没有使用synchronized优雅代码少,不过一些特殊的情况 还是需要它的。附上一些例子代码:

package com.jit.test;

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

public class AttemptLocking {

	private ReentrantLock lock = new ReentrantLock();

	public void untimed() {
		boolean captured = lock.tryLock();
		try {
			System.out.println("tryLock(): " + captured);
			System.out.flush();
		} finally {
			if (captured)
				lock.unlock();
		}
	}

	public void timed() {
		boolean captured = false;
		try {
			captured = lock.tryLock(2, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			throw new RuntimeException();
		}
		try {
			System.out.println("tryLock(2,TimeUnit.SECONDS): " + captured);
			System.out.flush();
		} finally {
			if (captured)
				lock.unlock();
		}
	}

	public static void main(String[] args) {
		final AttemptLocking al = new AttemptLocking();
		al.untimed();
		al.timed(); 
		new Thread() {
			{ 
				setDaemon(true);
			}
			public void run() {
				al.lock.lock();
				System.out.println("Acquired");
			}
		}.start();
		Thread.yield();
		al.untimed();
		al.timed();
	}
}

最后补充下: synchronized比较死心眼,锁着的时候会一直等待该资源释放。 而ReentrantLock尝试获取但最终未获取锁,不会总等待。而是会决定离开去执行其他一些事情 。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。