本篇文章给大家带来的内容是关于java线程中断与阻塞有什么不同?java线程中断与阻塞的对比,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
很多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结束); }}
相关推荐:
详解java多线程编程中locksupport类的线程阻塞用法
java中多线程阻塞和唤醒的示例代码
以上就是java线程中断与阻塞有什么不同?java线程中断与阻塞的对比的详细内容。
