美文网首页
对比LOCK的各种加锁方法

对比LOCK的各种加锁方法

作者: felix_feng | 来源:发表于2016-08-18 13:55 被阅读127次

    package fengchao.pubcli.mulitThread;

    import java.util.concurrent.TimeUnit;

    import java.util.concurrent.locks.Lock;

    import java.util.concurrent.locks.ReentrantLock;

    public class TestlockInterruptibly {

    public static void main(String[] args){

    Thread i1 = new Thread(new RunIt3());

    Thread i2 = new Thread(new RunIt3());

    i1.start();

    i2.start();

    i2.interrupt();

    }

    }

    class RunIt3 implements Runnable{

    private static Lock lock = new ReentrantLock();

    public void run(){

    try{

    //lock.lock();    //优先获取锁

    //lock.lockInterruptibly();  //优先中断 如果检测到interrupt标志为true,则立刻抛出InterruptedException异常

    lock.tryLock();  //尝试获取 获取不到锁抛出InterruptedException异常

    //lock.tryLock(10,TimeUnit.SECONDS);

    System.out.println(Thread.currentThread().getName() + " running");

    TimeUnit.SECONDS.sleep(20);

    lock.unlock();

    System.out.println(Thread.currentThread().getName() + " finished");

    }

    catch (InterruptedException e){

    System.out.println(Thread.currentThread().getName() + " interrupted");

    }

    }

    }

    相关文章

      网友评论

          本文标题:对比LOCK的各种加锁方法

          本文链接:https://www.haomeiwen.com/subject/fgyvsttx.html