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)。

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

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

    文件夹

  • 相关阅读:
    《网络攻防第四周作业》
    《网络攻防第三周作业》20179313
    15.javaweb XML详解教程
    小程序新功能:直接进入内嵌网页!
    为什么要创业?听听扎克伯格怎么说
    面试官:“还有什么问题问我吗?”我...
    双十一为何规则复杂,套路多多
    如何设置电信光猫?图解手把手教你(超级详细)
    14.javaweb AJAX技术详解
    android黑科技系列——自动注入代码工具icodetools
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6994256.html
Copyright © 2011-2022 走看看