JAVA线程的中断

每个线程都有一个boolean类型的标志来表明线程是否发生了中断,并且包含了中断相关的函数:interrupt()用于设置线程的中断状态为true,isInterrupted()用于返回线程的中断状态,interrupted()方法用于清除中断状态,并返回之前的中断状态。
当线程在调用sleep()或者wait()时,对中断的表现为抛出InterruptedException异常并清除中断状态,所以可以使用try-catch并在catch中写阻塞时被中断的处理方法:

/**
 *
 * @author jianbinggouzi
 */
public class MainClass{
    public static void main(String args[]){
        Object obj = new Object();
        
        Thread t2= new Thread(){
            public void run(){
               
                try{
               		 synchronized(obj){
						System.out.println("hello");
                		//obj.notify();
					}
                	
                }
                }catch(Exception e){
                    e.printStackTrace();
                }
               
            }
        };
        
        Thread t1 = new Thread(){
            
            public void run(){
                synchronized(obj){
             
                try {
                   
                    System.out.println("t1");
                    
                    obj.wait();
                    
                    System.out.println("finish");
                 
                }
                catch(InterruptedException e){
                   System.out.println("interrupted");
                    return;
                }
                catch (Exception ex) {
                    Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                }
                }
               
            }
        };
        t1.start();
        t2.start();
        new Thread(){
            int n=0;
            public void run(){
                
                while(true){
                    try{
                         Thread.sleep(1000);
                         if(n++>1){
                             t1.interrupt();
                         }
                         System.out.println(t1.getState()+" "+t2.getState());
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }.start( 
        
    }
}


结果:在这里插入图片描述

当线程没有处在阻塞状态时如果发生中断,线程将会保持运行下去直到运行到有对中断状态检查的地方(也就是说,由线程自己控制什么时候响应中断):

/**
 *
 * @author jianbinggouzi
 */
public class MainClass {
   
    public static void main(String args[]){
        
   
        
        Thread thread = new Thread(){
            public void run(){
                while(!Thread.currentThread().isInterrupted()){
                    System.out.println("running");
                }
                System.out.println("finish");
            }
        };
        thread.start();
        
        new Thread(){
            int n=0;
            public void run(){
                
                while(true){
                    try{
                         Thread.sleep(1000);
                         if(n++>1){
                             thread.interrupt();
                         }
                       
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }
}

结果:
在这里插入图片描述
在线程池中,可以用submit(Runnable r)方法返回的Future实例来管理线程池中的线程,Future的cancel方法参数为true时,表示设置一个正在运行的线程的中断标记,为false时表示不设置线程的中断标记,适用于“如果线程还没启动,就取消这个线程,否则就不取消”:
当cancel(true)时:

/**
 *
 * @author jianbinggouzi
 */
public class ExecutorServiceTest {
    
    private ExecutorService service = Executors.newFixedThreadPool(10);
    
    private ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
    
   
    Future futures[] = new Future[2];
     
    public ExecutorServiceTest(){
        Runnable t = new Runnable(){
          public void run(){
              try{
                  System.out.println(Thread.currentThread().getId()+"start");
                  Thread.sleep(1000);
                  System.out.println(""+Thread.currentThread().getId()+"finish1");
              }catch(InterruptedException ex){
                  System.out.println(""+Thread.currentThread().getId()+"interrupted");
              }
              
              
          }  
        };
        for(int i=0;i<2;i++){
            futures[i] = threadPoolExecutor.submit(t);
        }

        try{
            Thread.sleep(200);
            System.out.println(futures[0].cancel(true)+" "+futures[1].cancel(true));
            
        
        }catch(Exception e){
            
        }
        
        
    }
    
}

输出:
在这里插入图片描述
cancel(false)时:

/**
 *
 * @author jianbinggouzi
 */
public class ExecutorServiceTest {
    
    private ExecutorService service = Executors.newFixedThreadPool(10);
    
    private ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
    
    Future futures[] = new Future[2];
     
    public ExecutorServiceTest(){
        Runnable t = new Runnable(){
          public void run(){
              try{
                  System.out.println(Thread.currentThread().getId()+"start");
                  Thread.sleep(1000);
                  System.out.println(""+Thread.currentThread().getId()+"finish1");
              }catch(InterruptedException ex){
                  System.out.println(""+Thread.currentThread().getId()+"interrupted");
              }
              
              
          }  
        };
        for(int i=0;i<2;i++){
            futures[i] = threadPoolExecutor.submit(t);
        }

        try{
            Thread.sleep(200);
            System.out.println(futures[0].cancel(false)+" "+futures[1].cancel(false));
            
        
        }catch(Exception e){
            
        }
        
        
    }
    
}

输出:在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值