2011-01-07 159 views
1

我米使用Java而我會嘗試下面的代碼問題在啓動線程

public RunnableThread(String threadName){ 

    thread = new Thread(this,threadName); 
    System.out.println(thread.getName()); 
    thread.start(); 
    boolean status=thread.isAlive(); 
} 

但是當I M檢查線程其返回我的不實的狀態。

我沒有得到什麼可能是問題。

感謝您提前的建議。

其實我的run()方法有很多代碼要執行。我的main()方法的一部分代碼如下: JumboScrapeThread jumbThread = new JumbocrapeThread(「jubmThread」); Thread scraper = new Thread(jumbThread,「scraper」); scraper.start();我們知道當我們調用thread.start()時,它在內部調用run()方法。 但我在啓動線程時遇到問題,所以我的run()方法沒有被調用。

我m使用sellinium線程所以有任何可能性,因爲它我得到問題..?

+0

什麼是run()方法呢? – krakover 2011-01-07 14:02:25

+1

你在thread.run()裏面做了什麼。也許它在檢索isAlive值之前完成? – fmucar 2011-01-07 14:08:28

+0

現在我得到的線程狀態爲活着,但因爲我們知道start()內部調用run()方法,但在我的情況下運行方法沒有得到調用。你建議我這樣做? – saggy 2011-01-08 06:19:50

回答

0

可能是因爲線程在您致電isAlive()之前已經啓動並完成。 JVM不保證執行線程的順序,除非您進行明確的同步。

1

線程在run()方法結束後立即結束,因此在調用isAlive()方法時線程的狀態可能爲'false',儘管JVM對此沒有任何保證(所謂的競爭條件是否返回true或false)。你應該在run方法中加入一些東西。

1

因爲Thread需要一個Runnable或Thread作爲輸入,我不確定你的RunnableThread的類型是什麼,以及你是否重寫了run()方法。

如果它爲空,則線程將完成執行,在這種情況下,活動返回false。

2

可能是一個典型的競爭狀態:調用start()開始創建並最終運行一個新的線程,而該過程已經到達線程官方認爲前階段的isAlive()叫的過程「開始」(或,可能在它完成運行後)。

0

您可以使用同步等待您的線程完全啓動。

代碼

public class Main { 

    static class RunnableThread implements Runnable { 

     private Thread thread; 
     private Object waitForStart = new Object(); 

     public RunnableThread(String threadName) { 

      thread = new Thread(this, threadName); 
      System.out.println(thread.getName()); 


      synchronized (waitForStart) { 
       thread.start(); 
       try { 
        waitForStart.wait(); 
       } catch (InterruptedException ex) { 
       } 
       boolean status = thread.isAlive(); 
       System.out.println(status); 
      } 
     } 

     public void run() { 

      synchronized (waitForStart) { 
       waitForStart.notifyAll(); 
      } 

      // Do a bunch of stuff 
      try { 
       Thread.sleep(4000); 
      } catch (InterruptedException ex) { 
      } 

      System.out.println("Thread finished."); 
     } 
    } 

    public static void main(String[] args) { 
     RunnableThread thread = new RunnableThread("MyThread"); 
    } 
}