zoukankan      html  css  js  c++  java
  • 安全的停止一个线程

    采用interrupt()+ 检测isInterrupted() / interrupted()异常捕获

    package com;
    
    public class MyThread extends Thread {
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		super.run();
    		try {
    			for (int i = 0; i < 500000; i++) {
    				if (this.interrupted()) {
    					System.out.println("已经是停止状态了,我要退出!");
    					throw new InterruptedException();
    				}
    				System.out.println("i=" + (i + 1));
    			}
    		} catch (InterruptedException e) {
    			System.out.println("进MyThread.java   run 方法的catch了");
    			e.printStackTrace();
    		}
    
    	}
    }
    

      

    package com;
    
    public class Run {
    public static void main(String[] args) {
    	try {
    		MyThread thread = new MyThread();
    		thread.start();
    		Thread.sleep(1000);
    		thread.interrupt();
    		System.out.println("是否停止1?="+thread.interrupted());
    		System.out.println("是否停止1?="+thread.interrupted());
    	} catch (InterruptedException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }
    }
    

      

  • 相关阅读:
    奶酪真香
    规格说明书
    33
    111
    出题
    随笔 01
    我爱奶酪
    用户规格说明书
    第二次结对作业
    结对作业1
  • 原文地址:https://www.cnblogs.com/mobaids/p/8007441.html
Copyright © 2011-2022 走看看