java中ReentrantLock类的tryLock和tryLock的例子和用法

ReentrantLock类的tryLock和tryLock(时间) 

tryLock的方法就是试一下,如果能得到锁,就返回真,如果当时得不到,马上就返回假,绝不等。tryLock(时间)的用法就是 在规定的时间内设法得到锁。如果在规定的时间内最终不能得到锁,就返回假。注意,这个方法是可以被打断的,打断后的处理方法和上面的例子 lockInterruptibly的处理一样。
例1.9.8_a:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
class A {
    private ReentrantLock lock = new ReentrantLock();
    int ticketNum = 10;
    public void buyOne() {
        System.out.println("just before lock.lockInterruptibly();");
        boolean succeed = lock.tryLock();
        if (succeed) {
            System.out.println(Thread.currentThread().getName()
                    + "ticketNum is" + ticketNum);
            if (ticketNum > 0) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticketNum--;
                System.out
                        .println("模仿select * from table for update,执行的很慢,买了一张"
                                + Thread.currentThread().getName()
                                + "ticketNum is" + ticketNum);
            }
            lock.unlock();
        }else{
            System.out.println("没获得锁,一张");
        }
    }

    public void buyBatch(int num) throws InterruptedException {
        System.out.println("just before lock.lockInterruptibly();");
        boolean succeed = false;
        boolean sleepSucceed = false;
        succeed = lock.tryLock(2, TimeUnit.SECONDS);
        if (succeed) {
            System.out.println("Thread.currentThread().getName()+ticketNum is"
                    + ticketNum);
            try {
                Thread.sleep(5000);
                sleepSucceed=true;
            } catch (InterruptedException e) {
         

更多请见:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner6_web.html#ReentrantLocktryLockUsage

 

你可能感兴趣的:(java)