欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java中Lock,tryLock,lockInterruptibly有什么区别?-线程在sleep或wait,join, 此时如果别的进程调用此进程的 interrupt方法,此线程会被唤醒并被要求处理InterruptedException;(thread在做IO操作时也可能有类似行为,见java thread api)   2. 此线程在运行中, 则不会收到提醒。但是 此线程的 “打扰标志”会被设置, 可以通过isInterrupted查看并 作出处理。

最编程 2024-07-28 19:39:51
...




先看lock()方法

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

/**
 * @author 作者 E-mail:
 * @version 创建时间:2015-10-23 下午01:47:03 类说明
 */
public class TestLock
{
    // @Test
    public void test() throws Exception
    {
        final Lock lock = new ReentrantLock();
        lock.lock();

        
        Thread t1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " interrupted.");
            }
        },"child thread -1");
        
        t1.start();
        Thread.sleep(1000);
        
        t1.interrupt();
        
        Thread.sleep(1000000);
    }
    
    public static void main(String[] args) throws Exception
    {
        new TestLock().test();
    }
}


用eclipse对这个程序进行debug发现,即使子线程已经被打断,但是子线程仍然在run,可见lock()方法并不关心线程是否被打断,甚至说主线程已经运行完毕,子线程仍然在block().


而使用LockInterupptibly,则会响应中断

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

/**
 * @author 作者 E-mail:
 * @version 创建时间:2015-10-23 下午01:53:10 类说明
 */
public class TestLockInterruptibly
{

    // @Test
    public void test3() throws Exception
    {
        final Lock lock = new ReentrantLock();
        lock.lock();

        Thread t1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    lock.lockInterruptibly();
                }
                catch(InterruptedException e)
                {
                    System.out.println(Thread.currentThread().getName() + " interrupted.");
                }
            }
        }, "child thread -1");

        t1.start();
        Thread.sleep(1000);

        t1.interrupt();

        Thread.sleep(1000000);
    }

    public static void main(String[] args) throws Exception
    {
        new TestLockInterruptibly().test3();
    }
}


try{
      Thread.sleep(2000);
      lock.lockInterruptibly();
   }catch(InterruptedException e){
       System.out.println(Thread.currentThread().getName()+" interrupted.");
}

 

  t1.start();
  t1.interrupt();
  Thread.sleep(1000000);

 

如果将代码改成这样,那么将会在在阻塞之前已经中断,此时再lockInterruptibly()也是会相应中断异常的

 

 

 

 

转自:https://www.zhihu.com/question/36771163

推荐阅读