Java 线程中断(interrupt)与阻塞 (park)的区别

  很多Java开发人员(包括我),尤其是刚进入软件行业的新手,认为Java设置线程中断就是表示线程停止了,不往前执行了,

 Thread.currentThread().interrupt()

   其实不是这样的,线程中断只是一个状态而已,true表示已中断,false表示未中断

//获取线程中断状态,如果中断了返回true,否则返回false
Thread.currentThread().isInterrupted()

  设置线程中断不影响线程的继续执行,但是线程设置中断后,线程内调用了wait、jion、sleep方法中的一种, 立马抛出一个 InterruptedException,且中断标志被清除,重新设置为false。

class Thread2 implements  Runnable{

        @Override
        public void run() {
            try {
                System.out.println();
                System.out.println(hread.currentThread().isInterrupted());//输出false
                Thread.currentThread().interrupt();//当前线程中断
                System.out.println("Thread.currentThread().isInterrupted());//输出true
                Thread.sleep(3000);//中断后执行sleep会抛出异常
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("Thread.currentThread().isInterrupted());//输出false
            }
           
        }
    }

该如何让线程真正停止不往前执行呢:

 真正让线程停止下来(阻塞),Java提供了一个较为底层的并发工具类:LockSupport,该类常用的方法有两个,1 

park(Object blocker) 表示阻塞指定线程,参数blocker当前线程对象   2 unpark(Thread thread) 唤醒指定线程,参数thread指定线程对象 
示例:
     public void test_LockSupport(){
          Thread thread=new Thread(new Thread_park());
          thread.start();//阻塞当前线程
          Thread thread2=new Thread(new Thread_unpark(thread));
          thread2.start();//唤醒被阻塞的线程
      }

      class Thread_park implements  Runnable{
        @Override
        public void run() {
            System.out.println("Thread_park开始");
            LockSupport.park(this);//阻塞当前线程
            System.out.println("Thread_park结束");
         }
      }

     class Thread_unpark implements  Runnable{
        private Thread thread;

        public Thread_unpark(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            System.out.println("Thread_unpark开始");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockSupport.unpark(thread);//唤醒被阻塞的线程
            System.out.println("Thread_unpark结束");
        }
    }

猜你喜欢

转载自www.cnblogs.com/tfzjm/p/9647639.html