标签:
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();
}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) {
}
}
}
}
明显上面不是我们想要的结果。我们需要的是每一个线程执行过程都是独立的,打印出来希望的结果是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) {
}
}
}
}
}
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) {
}
}
}
}
java.util.concurrent.locks lock锁【2】
标签:
原文地址:http://blog.csdn.net/gaodml/article/details/42812355