java线程池学习--4

java代码:
package com.test0117;

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

public class AttemptLocking {
	private ReentrantLock lock = new ReentrantLock();
	public void untimed(){
		boolean captured = lock.tryLock();
		try{
			System.out.println("tryLock():"+captured);
		}finally{
			if(captured)lock.unlock();
		}
	}
	public void timed(){
		boolean captured = false;
		try{
			captured = lock.tryLock(2, TimeUnit.SECONDS);
			
		} catch (InterruptedException e) {
			throw new RuntimeException();
		}
		try{
			System.out.println("tryLock(2, TimeUnit.SECONDS):"+captured);
		}finally{
			if(captured)
			lock.unlock();
		}
	}
	public static void main(String[] args) {
		final AttemptLocking al = new AttemptLocking();
		al.untimed();
		al.timed();
		
		new Thread(){
			{setDaemon(true);}
			public void run(){
				al.lock.lock();
				System.out.println("acquired");
			}
		}.start();
		Thread.yield();
		al.untimed();
		al.timed();
	}
}



输出结果:
tryLock():true
tryLock(2, TimeUnit.SECONDS):true
acquired
tryLock():false
tryLock(2, TimeUnit.SECONDS):false

看到结果很迷糊。。。有大侠经过,讨论下,谢谢。

你可能感兴趣的:(java,thread)