对比LOCK的各种加锁方法

2016-08-18  本文已影响127人  felix_feng

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");

}

}

}

上一篇下一篇

猜你喜欢

热点阅读