zoukankan      html  css  js  c++  java
  • 从头认识java-17.2 线程中断(interrupt)

    这一章节我们来讨论一下线程中断(interrupt)。

    1.什么是线程中断(interrupt)?

    就是在多线程执行的时候,我们给线程贴上一个中断的标记。可是不要求线程终止。

    2.样例:

    中断的样例:

    package com.ray.ch17;
    
    public class Test2 {
    	public static void main(String[] args) {
    		PrintA printA = new PrintA();
    		Thread threadA = new Thread(printA);
    		threadA.start();
    	}
    }
    
    class PrintA implements Runnable {
    	private static int i = 0;
    
    	@Override
    	public void run() {
    		while (!Thread.currentThread().isInterrupted()) {
    			System.out.println("PrintA");
    			if (i == 2) {
    				Thread.currentThread().interrupt();
    			}
    			i++;
    		}
    	}
    }
    


    输出:

    PrintA
    PrintA
    PrintA

    不中断的样例:

    package com.ray.ch17;
    
    public class Test2 {
    	public static void main(String[] args) {
    		PrintB printB = new PrintB();
    		Thread threadB = new Thread(printB);
    		threadB.start();
    	}
    }
    
    class PrintB implements Runnable {
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 5; i++) {
    			System.out.println("PrintB");
    			Thread.currentThread().interrupt();
    		}
    	}
    }


    输出:

    PrintB
    PrintB
    PrintB
    PrintB
    PrintB

    由上面的两个样例我们能够看出,interrupt仅仅是贴上一个中断的标记,不会强制中断。

    3.interrupt与sleep的冲突

    由于当使用sleep在interrupt之后使用,sleep将会去掉interrupt这个标记

    冲突代码。以下的代码将会无限输出:

    package com.ray.ch17;
    
    public class Test2 {
    	public static void main(String[] args) {
    		PrintA printA = new PrintA();
    		Thread threadA = new Thread(printA);
    		threadA.start();
    	}
    }
    
    class PrintA implements Runnable {
    	private static int i = 0;
    
    	@Override
    	public void run() {
    		while (!Thread.currentThread().isInterrupted()) {
    			System.out.println("PrintA");
    			if (i == 2) {
    				Thread.currentThread().interrupt();
    				try {
    					Thread.currentThread().sleep(50);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			i++;
    		}
    	}
    }
    


    总结:这一章节主要介绍线程中断(interrupt)。

    这一章节就到这里,谢谢。

    -----------------------------------

    文件夹

  • 相关阅读:
    Android UI法宝的设计资源的开发
    Ural 1309 Dispute (递归)
    ZOJ3827 ACM-ICPC 2014 亚洲区域赛的比赛现场牡丹江I称号 Information Entropy 水的问题
    myeclipse如何恢复已删除的文件和代码
    在C#主线程和子线程将数据传递给对方如何实现
    SSh框架结构(Struts2.1+Hibernate4.0+Spring3.1)
    基于大数据分析的安全管理平台技术研究及应用【摘录】
    ulimit -t 引起的kill血案
    Oracle RAC 环境下的连接管理
    SMTP协议--在cmd下利用命令行发送邮件
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6994256.html
Copyright © 2011-2022 走看看