2011-01-07 165 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"); 
    } 
}