MyException - 我的异常网
当前位置:我的异常网» 互联网 » ReentrantLock()重入锁根本使用例子

香港六合彩六合网:ReentrantLock()重入锁根本使用例子

香港六合彩现场直播 www.hppyv.com  网友分享于:2018-05-05  浏览:0次
ReentrantLock()重入锁基本使用例子
 香港六合彩现场直播 www.hppyv.com package com.bjsxt.height.lock020;

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

public class UseCondition {

	private Lock lock = new ReentrantLock();//重入锁。
	private Condition condition = lock.newCondition();//与 wait() 和 notify方法相同。
	public void method1(){
		try {
			lock.lock();
			System.out.println("当前线程:" + Thread.currentThread().getName() + "进入等待状态..");
			Thread.sleep(3000);
			System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁..");
			condition.await();	// Object wait
			System.out.println("当前线程:" + Thread.currentThread().getName() +"继续执行...");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("释放锁method1");
			lock.unlock();
		}
	}
	
	public void method2(){
		try {
			lock.lock();
			System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..");
			Thread.sleep(3000);
			System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒..");
			condition.signal();		//Object notify
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("释放锁method2");
			lock.unlock();
		}
	}
	
	public static void main(String[] args) {
		
		final UseCondition uc = new UseCondition();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				uc.method1();
			}
		}, "t1");
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				uc.method2();
			}
		}, "t2");
		t1.start();

		t2.start();
	}
	
	
	
}

?

文章评论

软件开发程序错误异常香港六合彩现场直播Copyright © 2009-2015 MyException 版权所有
656| 673| 313| 137| 872| 589| 548| 808| 589| 509|