Wrong IsAlive() behaviour in Thread - java

I have just seen problem in my below code in isAlive method , it will return false even thread.start() method has been called, even i also tried to add some sleep in main thread as well as my thread object but still it gives same behavior.
public class ThreadBehaviour implements Runnable {
private Thread t;
ThreadBehaviour() {
t = new Thread();
t.setName("hello");
}
public void start() throws InterruptedException {
if (!t.isAlive()) {
t.start();
//Thread.currentThread().sleep(1000L);
//t.sleep(3000l);
System.out.println(t.getName() + " Running....." + t.isAlive());// why is Alive is false here?
}
}
public static void main(String args[]) throws InterruptedException {
ThreadBehaviour myThread = new ThreadBehaviour();
myThread.start();
}
#Override
public void run() {
t.run();
}
}

Your Thread that you made does nothing, so it instantly finishes and dies.
Consider this:
t = new Thread(() -> {
while (true) {
System.out.println("I'm running...");
}
});
and try again.

Read the java doc
isAlive();
Tests if this thread is alive. A thread is alive if it has been
started and has not yet died.
You only instantiate in constructor without started. So the thread is not started.

Related

Memory Consistency Properties explanation

I am looking at https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility and having trouble understanding what this means - "All actions in a thread happen-before any other thread successfully returns from a join on that thread." Can I please get an example on what this means and what is the happen-before guarantee in the example.
If you have he following code
public class Test {
public static int i = 1;
public static void main(String[] args) throws Exception {
System.out.println("Start main");
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("Start second");
i = 10;
}
});
t.start();
t.join();
System.out.println("After join");
System.out.println(i); //should print 10
}
}
Everything which is done inside run() method happens before main thread gets control back from t.join();. That is why static variable i will have value 10 when printed in main thread.

Why run() method defined is not called on call of start by Thread?

I was just experimenting some code around Thread class and I get stuck at something, Well firstly have a look at my code
class ThreadExample implements Runnable
{
String threadName;
Thread thread;
public ThreadExample()
{
thread=new Thread();
thread.start();
}
public void run()
{
System.out.println("Thread "+getThreadName()+" is being executed");
}
void setThreadName(String string)
{
threadName=string;
thread.setName(string);
}
String getThreadName()
{
return thread.getName();
}
public static void main(String string[]) throws InterruptedException
{
ThreadExample threadExample= new ThreadExample();
threadExample.setThreadName("Thread !");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 2");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 3");
Thread.sleep(500);
}
}
Well I think this code is very simple and Everyone should have got my intentions although When I am running this program It just get complete without even calling run() method even I make main Thread to wait for sometime until the child Thread which is ThreadExample completes. I am new to this so sorry if I have forgotten some thing. Thanks in advance.
You created a Runnable type and never passed it into a thread context. You'll want to add it to the Thread. I would do something like:
String threadName;
Thread thread;
public ThreadExample() {
thread=new Thread(this);
}
public void startThread() {
thread.start();
}
The Thread class accepts a Runnable as an argument.
You never call run() method. You rather call start, which you are already doing in ThreadExample() constructor, but it has some mistakes I will explain:
In java you have 2 options to deal with Threads. First is to inherit from Thread class, so you can call start() method from it and the code inside run() will be executed. The second option is to create a Runnable, which seems the option you are choosing, but to run this you have to create a Thread like this:
ThreadExample runnable = new ThreadExample();
Thread myThread = new Thread(threadExample);
And then you can call myThread.start(); when you are ready to start your thread.
As John Vint has pointed out, the Thread class needs a Runnable target. I edited your program a little :
public class NewThreadExample implements Runnable{
String threadName;
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public static void main(String[] args) throws InterruptedException {
NewThreadExample threadTarget = new NewThreadExample();
threadTarget.setThreadName("Dushyant");
Thread thread = new Thread(threadTarget);
System.out.println("Thread created and going to start");
thread.start();
System.out.println("Thread sleeping");
Thread.sleep(2000);
System.out.println("Program done");
}
#Override
public void run() {
System.out.println(this.getThreadName() + " is running...");
}
}
gives
Thread created and going to start
Thread sleeping
Dushyant is running...
Program done
To run this implementation class, create a Thread object, pass Runnable implementation class object to its constructor. Call start() method on thread class to start executing run() method.
You missed following two lines:
Thread thread1 = new Thread(threadExample);
thread1.start();
class ThreadExample implements Runnable
{
String threadName;
Thread thread;
public ThreadExample()
{
}
public void run()
{
System.out.println("Thread "+getThreadName()+" is being executed");
}
void setThreadName(String string)
{
threadName=string;
thread.setName(string);
}
String getThreadName()
{
return thread.getName();
}
public static void main(String string[]) throws InterruptedException
{
ThreadExample threadExample= new ThreadExample();
threadExample.setThreadName("Thread !");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 2");
//threadExample=new ThreadExample();
//threadExample.setThreadName("Thread 3");
Thread.sleep(500);
Thread thread1 = new Thread(threadExample);
thread1.start();
}
}

Calling non thread class from thread

My Problem:
I want to run a method from a Thread, which is no Thread but might take some time to execute (e.g. waiting for server response). It is important that my none thread method is in another class (the classes are Objects which are used in other classes too).
If you do this as in the example code, the whole program will pause for 10 seconds, but I want it to continue with other program code.
Is there a good way of doing this?
My code:
MyThread.java (extends Thread)
public Foo foo;
public void run() {
foo.bar();
}
Foo.java
public void bar() {
try {
Thread.sleep(10000);
// Represents other code that takes some time to execute
// (e.g. waiting for server response)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And a main method:
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.run();
System.out.println("Done!");
}
You don't want to call run() on the Thread, you want to call start().
Assuming MyThread extends Thread, you need to call start() not run().
Calling run() is just calling a method synchronously.
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.start(); // change here
System.out.println("Done!");
}
start() actually starts an OS thread to run your code on.
Use start() rather than run() on your thread. Or else it will be just like the main thread calling a method of another thread which means you are calling wait() on the main thread itself.
don't call run() method directly.
call start() method instead of run() method.
when call run() method directly
this thread go to main stack, and it run one by one.
class MyThread extends Thread{
public Foo foo;
public void run() {
foo.bar();
}
}
class Foo{
public void bar() {
try {
boolean responseCompleted = false;
boolean oneTimeExcution = false;
while(!responseCompleted){
if(!oneTimeExcution){
// Represents other code that takes some time to execute
oneTimeExcution = true;
}
if( your server response completed){
responseCompleted = true;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
System.out.println("Starting!");
t.start();
System.out.println("Done!");
}

Java Thread won't stop

I have a JRuby engine which evaluates some scripts and I want to close the thread if it takes more than 5 seconds.
I tried something like this:
class myThread extends Thread{
boolean allDone = false;
public void threadDone() {
allDone = true;
}
public void run() {
while(true) {
engine.eval(myScript);
if(allDone)
return;
}
}
(...)
th1 = new myThread();
th1.start();
try {
Thread.sleep(5000);
if(th1.isAlive())
th1.threadDone();
} catch(InterruptedException e) {}
if(th1.isAlive())
System.out.println("Still alive");
I also tried to kill the thread with th1.stop() or th1.interrupt() but the value retured by th1.isAlive() method is always true.
What can I do?
I want to add that myScript could be "while(1) do; end" and I cannot wait until it's completed. So I want to prevent scripts like that and kill the thread if it takes more than 5 seconds.
Another solution would be to use the built-in mechanism to interrupt threads:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
engine.eval(myScript);
}
}
...
th1 = new myThread();
th1.start();
try {
Thread.sleep(5000);
th1.interrupt();
}
This way, no need for an allDone field, and no risk in failing to synchronize.
To make your Thread stoppable you might want something like.
class MyTask implements Runnable {
public void run() {
try {
engine.eval(myScript);
} catch(ThreadDeath e) {
engine = null; // sudden death.
}
}
}
You can call Thread.stop(), but I suggest you read the warnings on this method first.
If you want a thread to run for up to 5 seconds, the simplest solution is for the thread to stop itself.
class MyTask implements Runnable {
public void run() {
long start = System.currentTimeMillis();
do {
engine.eval(myScript);
} while(System.currentTimeMillis() < start + 5000);
}
}
This assumes you want to run engine.eval() repeatedly. If this is not the case you may have to stop() the thread. It is deprecated for a good reason but it might be your only option.

communication between threads in java: stopping a thread if another thread has finished

How can I make a thread run only if the other thread is running too, meaning, if I return from run in one thread, then I want the other to stop running too,
my code looks something like this:
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
Thread thread1 = new Thread(serverMessagehandler);
Thread thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
I want to cause thread1 to stop running when thread2 stops running.
edit: detecting when thread2 stops running in order stop thread1 from running, and not how to stop thread1 from running
thanks
This minimal example should demonstrate the basic idea:
import java.io.*;
import java.util.concurrent.LinkedBlockingQueue;
public class Test {
static LinkedBlockingQueue<String> msgBuf = new LinkedBlockingQueue<String>();
static volatile boolean keepRunning = true;
static Thread thread1, thread2;
public static void main(String[] args) throws IOException {
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
thread1 = new Thread(serverMessagehandler);
thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
}
}
class ClientMessageHandler implements Runnable {
public void run() {
while (Test.keepRunning) {
try {
String msg = Test.msgBuf.take();
System.out.println("Eating " + msg);
} catch (InterruptedException ie) {
}
}
}
}
class ServerMessageHandler implements Runnable {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in;
try {
while (!(in = br.readLine()).equals("quit")) {
System.out.println("Feeding " + in);
Test.msgBuf.offer(in);
}
} catch (IOException e) {
}
Test.keepRunning = false;
Test.thread2.interrupt();
}
}
Edit for question clarification
I see two immediate options:
Option 1. Have the ClientMessageHandler implementation terminate the ServerMessageHandler as it terminates. This means the client needs a reference to the server thread.
public class ClientMessageHandler implements Runnable {
Thread serverThread;
public ClientMessageHandler(Thread srvThread) {
this.serverThread = srvThread;
}
public void run() {
try {
while (true) { ... }
} finally {
serverThread.interrupt();
}
}
}
Option 2. Use thread2.join() or a CountDownLatch to wait for thread2 to terminate. When control returns from the join (or CountDownLatch#await()).
ClientMessageHandler clientMessagehandler = new ClientMessageHandler();
ServerMessageHandler serverMessagehandler = new ServerMessageHandler();
Thread thread1 = new Thread(serverMessagehandler);
Thread thread2 = new Thread(clientMessagehandler);
thread2.start();
thread1.start();
thread2.join(); //blocks until the client terminates
thread1.interrupt();
Make sure that inside thread1's run method, you have some logical place where you can check the interrupt status (Thread#isInterrupted()) and decide to terminate. Also, you must take care to handle InterruptedException properly and either terminate or reset the interrupt flag.
A Thread will only stop when the run() method returns. The Thread#interrupt() only signals that a request for interruption has made. You still have to write the code in run() method accordingly that it periodically checks Thread#isInterrupted() and handle accordingly. E.g. check for it on every unit of task the Thread is doing, or on every certain progress when sort of progresslistener is attached.

Categories

Resources