Reputation: 13
I m using Java and i m trying below piece of code
public RunnableThread(String threadName){
thread = new Thread(this,threadName);
System.out.println(thread.getName());
thread.start();
boolean status=thread.isAlive();
}
but when i m checking the status of the thread its returning me false.
I m not getting what could be the issue.
Thanks for the suggestion in advance.
Actually my run() method has much code to execute.
My main() method has below piece of code as some of its part JumboScrapeThread jumbThread = new JumbocrapeThread("jubmThread"); Thread scraper = new Thread(jumbThread,"scraper"); scraper.start();
As we know when we call thread.start() ,it internally call run() method. but i m getting the problem in starting the thread,so my run() method is not getting called.
I m using the thread with sellinium so is there any possibility that i m getting issue because of it..?
Upvotes: 1
Views: 428
Reputation: 13638
You can use synchronization to wait for your thread to start completely.
Code
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");
}
}
Upvotes: 0
Reputation: 346536
Probably a classic race condition: calling start()
only begins the process of creating and eventually running a new thread, and the isAlive()
is called before that process has reached the stage where the thread is officially considered "started" (or, possibly, after it has finished running).
Upvotes: 2
Reputation: 5612
THats because Thread needs either a Runnable or a Thread as input and i am not sure whats the type of your RunnableThread and whether you have overridden the run() method.
If its empty, the thread would have finished execution, inwhich case the alive returns false.
Upvotes: 1
Reputation: 22741
The thread ends as soon as the run()
method ends, hence the status of the thread will probably be 'false' by the time the isAlive()
method is called, although the JVM makes no guarantees about this (a so-called race condition as to whether it returns true or false). You should put something in the run
method.
Upvotes: 1
Reputation: 403601
Possibly because the thread has started and finished before you call isAlive()
. The JVM makes no guarantees about the order in which threads are executed, unless you put in explicit synchronization.
Upvotes: 0