serrure java 锁

Vous devez libérer manuellement le verrou

lock.tryLock booléenne (de longue date, TimeUtil util), et continuer à essayer d'appliquer un temps de verrouillage, appliquer aux rendements réels

lock.lockInterruptibly () vide jette InterruptedException, les réclamations continues verrouillent, l'effet est équivalent à serrure.Serrure (), mais lockInterruptibly () pour annuler l'attente dans le thread principal, après l'abolition de l'attente jetteront une 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; 
    }

}

Les résultats d'exploitation 

Publié 16 articles originaux · louange gagné 3 · Vues 4530

Je suppose que tu aimes

Origine blog.csdn.net/qq_29697901/article/details/90175924
conseillé
Classement