javaスレッドを閉じるにはどうすればいいですか?

2444 ワード

          
    1.        ,       ,    run         。 
    2.    stop        (         ,  stop suspend、resume  ,            )。
    3.    interrupt      。 

1.            
     run      ,      。   run          。                     ,              。      ,               , while  。            ,    while(true){……}   。    while            ,           boolean     ,          true false   while      。                    。 
package chapter2; 
public class ThreadFlag extends Thread 
{ 
    public volatile boolean exit = false; 
    public void run() 
    { 
        while (!exit); 
    } 
    public static void main(String[] args) throws Exception 
    { 
        ThreadFlag thread = new ThreadFlag(); 
        thread.start(); 
        sleep(5000); //      5  
        thread.exit = true;  //     thread 
        thread.join(); 
        System.out.println("    !"); 
    } 
} 
                   exit, exit true ,while    ,exit     false.   exit ,     Java   volatile,          exit  ,                   exit  , 

    2.   stop       
      stop                  。                : 
thread.stop(); 
                   ,   stop       ,           ,            ,            ,  ,      stop       。 

    3.   interrupt       
      interrupt              : 
    (1)        ,    sleep  。 
    (2)  while(!isInterrupted()){……}          。 
             interrupt  ,sleep       InterruptedException  ,               。                 interrupt  。 
package chapter2; 
public class ThreadInterrupt extends Thread 
{ 
    public void run() 
    { 
        try 
        { 
            sleep(50000);  //   50  
        } 
        catch (InterruptedException e) 
        { 
            System.out.println(e.getMessage()); 
        } 
    } 
    public static void main(String[] args) throws Exception 
    { 
        Thread thread = new ThreadInterrupt(); 
        thread.start(); 
        System.out.println(" 50           !"); 
        System.in.read(); 
        thread.interrupt(); 
        thread.join(); 
        System.out.println("      !"); 
    } 
} 
               : 
     50           ! 
    sleep interrupted 
          ! 
       interrupt   , sleep      ,        :sleep interrupted. 
      : Thread                 interrupt     。        interrupted(),         isInterrupted(),         interrupted            , isInterrupted               。  ,while (!isInterrupted())     while (!Thread.interrupted())。