Lock&Condition实现线程同步通信

Java1.5提供了锁机制,位于java.util.current.locks下面

Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,本身也应该是一个对象。
两个线程执行的代码片段要实现同步互斥的效果,它们徐用同一个Lock对象。锁是上在代表要操作的资
源的类的内部方法中,而不是线程代码中。
读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,写锁与写锁互斥
这是由JVM自己控制的,你只要上号相应的锁即可。如果你的代码只读数据,可以多人同时读,但不能同时写,那就上读锁;如果你的代码修改数据。
只能有一个在写,且不能同时读取,那就上写锁。总之,读的时候上读锁,写的时候上写锁。

  

package com.ronbay.thread.timer;

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

public class LockTest {
	public static void main(String[] args) {
		new LockTest().init();
	}
	
	private  void init(){
		final Outputer outputer = new Outputer();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					outputer.output("saiwegang");
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					outputer.output("shilongfei");
				}
			}
		}).start();
	}
	
	static class Outputer{
		Lock lock = new ReentrantLock();
		public void output(String name){
			int len = name.length();
			lock.lock();
			try {
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				lock.unlock();
			}
		}
	}
}

猜你喜欢

转载自ronbay.iteye.com/blog/2296999