class   Test   implements   Runnable 

      Thread   m_thread   =   null; 
      Test(){ 
            m_thread   =   new   Thread(this); 
            m_thread.start(); 
      } 
      public   viod   run(){ 
Thread   curThread=Thread.currentThread(); 
while   (m_thread   ==   curThread)   { 
Sytem.out.println("hellword"); 
try   { 
      Thread.sleep(200); 
}   catch   (InterruptedException   e)   { 
      e.printStackTrace(); 


System.out.println("out   of   thread"); 
        } 
        public   static   void   main(String   argv[]){ 
Test   a1=   new   Test(); 
Test   a2=   new   Test(); 
Test   a3=   new   Test();
Test   a4=   new   Test();  
        } 

什么时间out   of   thread会被打印??

解决方案 »

  1.   

    public void run() {
    Thread curThread = Thread.currentThread();
    while (m_thread == curThread) {
    System.out.println("hellword "+ number);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("out       of       thread");
    }
    线程每次切换到这里的时候,线程号已经变成了所执行的线程的id,这样做mthread == curthread 一直都成立,
    肯定无法执行到循环之外。
      

  2.   

    如果要查看线程的切换和结束,要用一个相对线程独立的标记来表示class random extends Thread{
    Thread m_thread = null;
    static int  = 0;
    int stop_number;
    random(int i) {
    m_thread = new Thread(this);
    stop_number = i;
    m_thread.start();
    } public void run() {
    //Thread curThread = Thread.currentThread();
    while (stop_number !=  &&  < 14) {

    ++;
    System.out.println("hellword "+ stop_number);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("out       of       thread");
    } public static void main(String argv[]) {
    random a1 = new random(4);
    random a2 = new random(8);
    random a3 = new random(11);


    random a4 = new random(13);


    }
    }