11-Java5的线程锁技术

package cn.itcast.demo.thread;

import java.util.concurrent.locks.ReentrantLock;


public class Lock {
	public static void main(String[] args) {
		new Lock().init();
	}
	private void init() {	
		final Outputer outputer = new Outputer();		// 在静态方法内不能创建内部类对象
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						e.printStackTrace();
					}
					outputer.output("helloworld");		// 要调用匿名内部类方法,必须在变量前+final修饰
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						e.printStackTrace();
					}
					outputer.output("zhangsan");		// 要调用匿名内部类方法,必须在变量前+final修饰
				}
			}
		}).start();
	}
	static class Outputer {
		// 创建线程锁对象
		java.util.concurrent.locks.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();
			}
		}
	}
}

 

posted @ 2017-08-17 17:56  半生戎马,共话桑麻、  阅读(78)  评论(0)    收藏  举报
levels of contents