java.util.concurrent.locks lock锁【2】

时间:2015-01-17 23:35:17   收藏:0   阅读:319

Lock 锁介绍


JDK1.5以前,我们实现线程同步都是通过synchroized关键字进行方法或者语句块锁定,以保证该关键字作用域内的操作都是原子性操作。

JDK1.5以后,提供的并发包提供了更强大的功能和更为灵活,最为关键的是需要手工释放锁,需要unlock必须在finally方法内。这是非常值得注意的事情。


介绍一下Lock接口。实现类有3个,分别是 普通锁,读写锁-写锁,读写锁-读锁。

技术分享


API文档给出了相近的说明和demo。

     Lock l = ...;
     l.lock();
     try {
         // access the resource protected by this lock
     } finally {
         l.unlock();
     }

我们写一个程序,分别输出11111,00000,这里加入sleep方法,防止cpu分配太快,导致看不到我们需要的效果,分别启用两个线程,做分别输出,当然这是一个线程不同步的程序。

public class WriteName {

	public static void main(String[] args) {
		final ShowName out = new ShowName();
		new Thread() {
			public void run() {
				out.output("11111");
			}
		}.start();
		new Thread() {
			public void run() {
				out.output("00000");
			}
		}.start();
	}
}

class ShowName {
	public void output(String str) {
		for (int i = 0; i < str.length(); i++) {
			System.out.print(str.charAt(i));
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
			}
		}
	}
}


某一次的打印结果   1010101010

明显上面不是我们想要的结果。我们需要的是每一个线程执行过程都是独立的,打印出来希望的结果是1111100000,上面的结果明显是cpu分配的时候,多线程执行出现了交叉。


如果按照我们以前线程同步的方式。我们可以使用synchroized关键字。

class ShowName {
	public synchronized void output(String str) {
		for (int i = 0; i < str.length(); i++) {
			System.out.print(str.charAt(i));
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
			}
		}
	}
}

或者

class ShowName {
	public void output(String str) {
		synchronized (this) {
			for (int i = 0; i < str.length(); i++) {
				System.out.print(str.charAt(i));
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}
			}
		}
	}
}

从JDK1.5以后我们有了更加灵活的方法。Lock锁

Lock接口下面有个三个实现类,我们这里使用普通锁。

技术分享

API里面有个非常容易看懂的demo,我们模仿改造一下我们的代码:

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

public class WriteName {

	public static void main(String[] args) {
		final ShowName out = new ShowName();
		final Lock lock = new ReentrantLock();
		new Thread() {
			public void run() {
				try {
					lock.lock();
					out.output("11111");
				} finally {
					lock.unlock();
				}
			}
		}.start();
		new Thread() {
			public void run() {
				try {
					lock.lock();
					out.output("00000");
				} finally {
					lock.unlock();
				}
			}
		}.start();
	}
}

class ShowName {
	public void output(String str) {
		for (int i = 0; i < str.length(); i++) {
			System.out.print(str.charAt(i));
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
			}
		}
	}
}


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!