您的位置:首页 > 编程语言 > Java开发

JDK5什么是新的线程锁技术(两)

2015-08-17 09:46 337 查看
一个. Lock线程同步实现互斥

Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也是一个对象。

两个线程运行的代码片段要实现同步相互排斥的效果。他们必须用同一个Lock对象。锁是上在代表要操作的资源的类的内部方法中,

而不是线程代码中。

public class LockTest {

public static void main(String[] args) {
new LockTest().init();
}

private void init() {
final Outputer outputer = new Outputer();

// 线程1
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
outputer.output("1111111111");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();

// 线程2
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
outputer.output("2222222222");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}

class Outputer {
private Lock lock = new ReentrantLock();
public void output(String name) {
lock.lock(); // 加锁
try {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
} finally {
lock.unlock(); // 释放锁
}
}
}
}


二. 读写锁实现线程同步相互排斥

读写锁分为读锁和写锁。多个读锁不相互排斥,读锁和写锁相互排斥,写锁与写锁相互排斥。这是由JVM自己控制的,我们仅仅要上好对应的锁就可以。

假设你的代码仅仅读数据,能够非常多人同一时候读。但不能同一时候写,那就上读锁;假设你的代码要改动数据,那仅仅能有一个人在写。且不能同一时候读取。那就上写锁。总之:读的时候上读锁,写的时候上写锁

/**
* 读写锁的案例
*/
public class ReadWriteLockTest {

public static void main(String[] args) {
final Queues queues = new Queues();

// 开启3个读的线程和3个写的线程
for (int i = 0; i < 3; i++) {
new Thread() {
public void run() {
while (true) {
queues.get();  // 调用读数据的方法
}
}
}.start();

new Thread() {
public void run() {
while (true) {
queues.put(new Random().nextInt(10000)); // 调用写数据的方法
}
}
}.start();
}
}
}

class Queues {
private Object data = null; // 共享数据, 仅仅能有一个线程写数据,但能有多个线程同一时候读数据
private ReadWriteLock rwl = new ReentrantReadWriteLock();

// 读的方法:用的是读锁readLock()
public void get() {
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " get ready to read data!

");
Thread.sleep((long) Math.random() * 1000);
System.out.println(Thread.currentThread().getName() + " have read data:" + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
rwl.readLock().unlock();
}
}

// 写的方法:用的是写锁writeLock()
public void put(Object data) {
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " get ready to write data。");
Thread.sleep((long) Math.random() * 1000);

this.data = data; // 改动共享数据
System.out.println(Thread.currentThread().getName() + " have write data:" + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
rwl.writeLock().unlock();
}
}
}
注意:释放锁的代码一定要放在finally里面,防止出现不可预知的异常的时候无法释放资源。

三. 读写锁的典型应用

/**
* 缓存的简单实现
*/
public class CacheDemo {

private Map<String, Object> cache = new HashMap<String, Object>();

private ReadWriteLock rwl = new ReentrantReadWriteLock();

public Object getData(String key) {
// 用户来读取value数据,则在进入程序后上读锁
rwl.readLock().lock();
Object value = null;
try {
value = cache.get(key);
if (value == null) {
// 读到的值为空则释放读锁,打开写锁,准备给value赋值
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
// 打开写锁还为空,则给value赋值xxx
if (value == null) {
value = "xxx";  // 实际应该去数据库中查询 queryDB()
cache.put(key, value);
}
} finally {
// 使用完写锁后关掉
rwl.writeLock().unlock();
}
// 释放写锁后,恢复读锁
rwl.readLock().lock();
}
} finally {
// 用户读完后释放掉读锁
rwl.readLock().unlock();
}
return value;
}
}


疑问:为何上写锁前要释放读锁?为何释放写锁后要又一次上读锁?

我们能够这样把对象锁看成现实中的门闩。一扇门仅仅能有一个门闩。

所以上写的门闩要释放读的门闩。

四. Condition实现线程同步通信

Condition的功能类似传统线程技术中的Object.wait和Object.notify功能, 一个锁累不能够有多个Condition, 即有多路等待和通知.

传统线程机制中一个监视器对象上仅仅有一路等待和通知, 要想实现多路等待和通知, 就必须使用多个同步监视器对象:

/**
* 三个Condition通信的场景
*/
public class ThreeConditionCommunication {

public static void main(String[] args) {
final Business business = new Business();

// 线程1
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
business.sub1(i);
}
}
}).start();

// 线程2
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
business.sub2(i);
}
}
}).start();

// 线程3
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
business.sub3(i);
}
}
}).start();

}

static class Business {
private int flag = 1;
Lock lock = new ReentrantLock();

Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();

public void sub1(int i) {
try {
lock.lock();
while (flag != 1) {
condition1.await();
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub1 thread sequence of  " + j + " ,loop of  " + i);
}
flag = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void sub2(int i) {
try {
lock.lock();
while (flag != 2) {
condition2.await();
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub2 thread sequence of  " + j + " ,loop of  " + i);
}
flag = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void sub3(int i) {
try {
lock.lock();
while (flag != 3) {
condition3.await();
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub3 thread sequence of  " + j + " ,loop of  " + i);
}
flag = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: