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( 
        
    }
}


结果:JAVA线程的中断_第1张图片

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

/**
 *
 * @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();

    }
}

结果:
JAVA线程的中断_第2张图片
在线程池中,可以用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){
            
        }
        
        
    }
    
}

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

你可能感兴趣的:(java)