java lock 锁

You need to manually release the lock

boolean lock.tryLock (long time, TimeUtil util); and continue to try to apply a lock time, apply to returns true

void lock.lockInterruptibly () throws InterruptedException; continuing claims lock, the effect is equivalent to lock.lock (), but lockInterruptibly () to cancel the wait in the main thread, after the abolition of waiting will throw an exception.

package com.iweb;

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

/**
 * Created by zh on 2019/4/29.
 */
public class Rep {


    Lock lock = new ReentrantLock();
    volatile boolean stop = false;


    // 通过 lock 申请锁
    private void t1() {
        lock.lock();
        try {
            while(!stop) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
   // 通过 lockInterruptibly 申请锁
    private void t2() {
        boolean l = false;
        try {
            lock.lockInterruptibly();
            l = true;
            while(!stop) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(Thread.currentThread().getName());
            }
            System.out.println(Thread.currentThread().getName() + " end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (l)
                lock.unlock();
        }
    }

    
    
    public static void main(String[] args) {
        Rep r = new Rep();

        Thread t1 = new Thread(()->r.t1(), "t1");
        t1.start();


        Thread t2 = new Thread(()->r.t2(), "t2");
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.interrupt(); // 停止t2持续申请但 会抛异常
        r.stop = true; 
    }

}

operation result 

Published 16 original articles · won praise 3 · Views 4530

Guess you like

Origin blog.csdn.net/qq_29697901/article/details/90175924