JDK5新特性之线程锁技术(二)

一. 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();
			}
		}
	}
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值