线程的打断

interrupt相关的三个方法:

public void interrupt()            //t.interrupt() 打断t线程(设置t线程某给标志位f=true,并不是打断线程的运行)
public boolean isInterrupted()     //t.isInterrupted() 查询打断标志位是否被设置(是不是曾经被打断过)
public static boolean interrupted()//Thread.interrupted() 查看“当前”线程是否被打断,如果被打断,恢复标志位

1. interrupt() :实例方法,设置线程中断标志(打扰一下,你该处理一下中断)
2. isInterrupted():实例方法,有没有人打扰我?
3. interrupted():静态方法,有没有人打扰我(当前线程)?复位!

 interrupt和sleep() wait() join()

sleep()方法在睡眠的时候,不到时间是没有办法叫醒的,这个时候可以用interrupt设置标志位,然后呢必须得catch InterruptedException来进行处理,决定继续睡或者是别的逻辑,(自动进行中断标志复位)

interrupt是否能中断正在竞争锁的线程

public class SleepHelper {
    public static void sleepSeconds(int seconds){
        try {
            Thread.sleep(seconds*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class T09_Interrupt_and_sync {

    private static Object o = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(()-> {
            synchronized (o) {
                SleepHelper.sleepSeconds(10);
            }
        });

        t1.start();

        SleepHelper.sleepSeconds(1);

        Thread t2 = new Thread(()-> {
            synchronized (o) {

            }
            System.out.println("t2 end!");
        });

        t2.start();

        t2.interrupt();
    }
}

//输出: t2 end!

结论:interrupt()不能打断正在竞争锁的线程synchronized()

如果想打断正在竞争锁的线程,使用ReentrantLock的lockInterruptibly()

import java.util.concurrent.locks.ReentrantLock;

public class T11_Interrupt_and_lockInterruptibly {

    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(()-> {
            lock.lock();
            try {
                SleepHelper.sleepSeconds(10);
            } finally {
                lock.unlock();
            }
            System.out.println("t1 end!");
        });

        t1.start();

        SleepHelper.sleepSeconds(1);


        Thread t2 = new Thread(()-> {
            System.out.println("t2 start!");
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println("t2 end!");
        });

        t2.start();

        SleepHelper.sleepSeconds(1);
        
        t2.interrupt();

    }
}

输出结果

t2 start!
java.lang.InterruptedException
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
	at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
	at com.example.demo.test.T11_Interrupt_and_lockInterruptibly.lambda$main$1(T11_Interrupt_and_lockInterruptibly.java:28)
	at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
	at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
	at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
	at com.example.demo.test.T11_Interrupt_and_lockInterruptibly.lambda$main$1(T11_Interrupt_and_lockInterruptibly.java:32)
	at java.lang.Thread.run(Thread.java:748)
t1 end!

优雅的结束线程

1. 自然结束(能自然结束就尽量自然结束)
2. stop() suspend() resume()
3. volatile标志
   1. 不适合某些场景(比如还没有同步的时候,线程做了阻塞操作,没有办法循环回去)
   2. 打断时间也不是特别精确,比如一个阻塞容器,容量为5的时候结束生产者,
      但是,由于volatile同步线程标志位的时间控制不是很精确,有可能生产者还继续生产一段儿时间
4. interrupt() and isInterrupted(比较优雅)

 

 

结合以上问题,JDK17版本中AQS的acquire方法中的中断机制在何处处理的,以下是acquire方法的代码: final int acquire(Node node, int arg, boolean shared, boolean interruptible, boolean timed, long time) { Thread current = Thread.currentThread(); byte spins = 0, postSpins = 0; boolean interrupted = false, first = false; Node pred = null; for (;;) { if (!first && (pred = (node == null) ? null : node.prev) != null && !(first = (head == pred))) { if (pred.status < 0) { cleanQueue(); // predecessor cancelled continue; } else if (pred.prev == null) { Thread.onSpinWait(); // ensure serialization continue; } } if (first || pred == null) { boolean acquired; try { if (shared) acquired = (tryAcquireShared(arg) >= 0); else acquired = tryAcquire(arg); } catch (Throwable ex) { cancelAcquire(node, interrupted, false); throw ex; } if (acquired) { if (first) { node.prev = null; head = node; pred.next = null; node.waiter = null; if (shared) signalNextIfShared(node); if (interrupted) current.interrupt(); } return 1; } } Node t; if ((t = tail) == null) { // initialize queue if (tryInitializeHead() == null) return acquireOnOOME(shared, arg); } else if (node == null) { // allocate; retry before enqueue try { node = (shared) ? new SharedNode() : new ExclusiveNode(); } catch (OutOfMemoryError oome) { return acquireOnOOME(shared, arg); } } else if (pred == null) { // try to enqueue node.waiter = current; node.setPrevRelaxed(t); // avoid unnecessary fence if (!casTail(t, node)) node.setPrevRelaxed(null); // back out else t.next = node; } else if (first && spins != 0) { --spins; // reduce unfairness on rewaits Thread.onSpinWait(); } else if (node.status == 0) { node.status = WAITING; // enable signal and recheck } else { long nanos; spins = postSpins = (byte)((postSpins << 1) | 1); if (!timed) LockSupport.park(this); else if ((nanos = time - System.nanoTime()) > 0L) LockSupport.parkNanos(this, nanos); else break; node.clearStatus(); if ((interrupted |= Thread.interrupted()) && interruptible) break; } } return cancelAcquire(node, interrupted, interruptible); } 我们知道线程打断分为,打断WAITING、TIMED_WAITING、BLOCKED三种状态,还可以打断运行中的线程,我已经知道了打断WAITING、TIMED_WAITING状态会抛出InterruptedException异常,在catch块中可以处理打断,而运行中的线程打断可以在线程执行代码中用isInterrupted方法来判断处理,那BLOCKED状态是由于线程竞争造成的阻塞状态,AQS提供了可打断竞争方式,那么在代码中是如何体现出它的BLOCKED可打断的呢?
03-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值