State of thread while in run() method (Java) - java

I am trying to understand multithreading in java. As I was going through the various states a Java thread can be in (new, Runnable, Running, Waiting/Blocked, Dead). I tried to run some simple code to check the states of the thread.
I created a class MyThread that extends Thread and overrode run() method.
package com.practice.threads;
public class MyThread extends Thread {
#Override
public void run() {
super.run();
System.out.println("Running Mythread.");
System.out.println("State of thread : " + this.getState()); // line 2
}
}
Now I have created a simple class to test the states of thread :
package com.practice.threads;
public class ThreadStateDemo {
/**
* #param args
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("State of thread : " + myThread.getState()); // line 1
myThread.start();
}
}
Running this class give the following output :
State of thread : NEW
Running Mythread.
State of thread : RUNNABLE
The output of line 2 is something I don't understand. When run() method of a thread instance is being executed, how can it be in RUNNABLE state? I saw mention of a RUNNING state in a book (SCJP Suncertified Programmer). Should it not show RUNNING?

The book has an (easy-to-make) error, the state is RUNNABLE, not RUNNING. There is no RUNNING state, see the JavaDoc:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
(My emphasis)
It's just an odd, slightly pedantic name, since technically, it's only running if the OS is running it. But it's "running" from the JVM's point of view.

The JVM doesn't control whether the thread is running or not, the OS does. The JVM only knows if it asked the OS to run the thread which is what makes it RUNNABLE.

Related

Deamon thread not working T1,T2,T3 are the classes. I wrote separately. What mistake did I make? Why is my deamon thread not reachable?

My code:
package multithreading;
public class JoinT1T2T3 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread is running");
}
else
{
System.out.println("Slave thread");
}
}
public static void main(String args[])
{
Thread t=new Thread();
t.setDaemon(true);
T1 thread1=new T1();
T2 thread2=new T2();
T3 thread3=new T3();
System.out.println("First Thread name is::: "+thread1.getName());
thread1.setName("XXXXXXXXXX");
System.out.println("First Thread After changing name::: "+thread1.getName());
System.out.println("First thread's id is :::"+thread1.getId());
thread1.start();
try
{
thread1.join(3000);
}
catch(Exception e)
{
System.out.println("-----------");
}
//thread2.start();
thread2.start();
thread3.start();
}
}
Why is my daemon not reachable? Please provide me an explanation and code.
T1,T2,T3 are three different classes. The main method is also the run method. I created a new thread instance. Still getting "code not reachable". Which is if{} else{} in run method.
You are getting the "not reachable" error because JoinT1T2T3#run() is never called anywhere.
To Reach JoinT1T2T3#run()
In order for a run() method to be called, an object of its containing class should be explicitly passed to a Thread at construction-time using Thread#(Runnable). For example:
Thread t = new Thread(new JoinT1T2T3());
Now, Thread t will call JoinT1T2T3#run() whenever it starts.
To Run t
Even if t is a daemon, it must still be start()'ed just like any other Thread, or else it will not run. (and thus JoinT1T2T3#run() will never be called) So you need to do this:
Thread t = new Thread(new JoinT1T2T3());
t.setDaemon(true);
t.start();
explaining "daemon" threads
Generally speaking, in Java the only functional difference between a deamon Thread and a non-daemon Thread is that "the Java Virtual Machine exits when the only threads running are all daemon threads" (source). Other than that, a daemon Thread behaves exactly like a non-daemon Thread, syntax and all. It must still be constructed with a Runnable and start()'ed, just like any other Thread.
However, because a daemon thread may be abruptly terminated when the JVM exits, daemons should be used sparingly. In particular, daemons should not be used for any I/O or resource cleanup. "Normal" guarantees about stuff like finally blocks and stack unwinding don't necessarily apply to daemon threads--if the JVM decides to exit, all daemons are immediately abandoned. (source)
Java daemons should be used only for background housekeeping, bookkeeping, metrics, non-critical monitoring, etc.

How to wake thread by condition

I have an activity running, of course, on UI thread and there is another thread running in background and communicating with activity using Handler post method(through looper).
When screen is turned of or application is hidden it continues to work.
So I need to stop this thread in onPause method and wake it up in onResume mehtod.
In my thread I have condition to pause it or to stop.
How to can I put thread to sleep in onPause method. And wake it up after activity is again in foreground.
I can do it with one object using monitor calling wait method and than notify on this object.
But is it good approach ? Or there is another way to do this elegantly.
Sounds like a good place to use a turnstile. Initialize a Semaphore with one permit:
Semaphore turnstile = new Semaphore(1);
Make your background activity periodically pass through the turnstile like so:
turnstile.acquire();
turnstile.release();
When the foreground thread wants the background thread to pause at the turnstile, it can lock the turnstile:
turnstile.acquire();
And when the foreground thread wants that background thread to start working again, it can unlock the turnstile():
turnstile.release();
Good software engineering practice would be to wrap the whole thing up in a Turnstile class with appropriately named methods for the foreground and background threads to call. I'll leave that as an exercise for the reader.
Android suggests using services for long term background tasks, but if you're just opening a new thread that is tied to your Android lifecycle, I don't think it would be bad to use a monitor and call wait/notify. Can you be more specific with what you are doing?
This is an overview of how I would stop and resume a stopped thread. (You may want to implement runnable in yours)
class ThreadDemo extends Thread {
private Object monitor; //This is the monitor
private boolean keepRunning = true;
private Thread t;
ThreadDemo(){
System.out.println("Creating thread");
}
public void callinOnResume(){
synchronized(monitor){
monitor.notify();
}
}
public void callinOnPause(){
try {
synchronized(monitor){
System.out.println(threadName + "Waiting");
monitor.wait();
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted " + e.toString());
}
}
public void run() {
System.out.println("Starting to loop.");
while (keepRunning) {
//stuff
}
System.out.println("Done looping.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
It is a bad practice to stop/resume a thread outside that thread. The thread must decide itself when to run and when to stop. As a result, the background thread should check periodically if its work is still needed, and the client (foreground) thread should issue some signals about that.
One way to issue signals is to form that signals as jobs of type Runnable and then execute them on a thread pool. So when the activity sleeps, it just does not issue signals.
The main problem when a background thread wants to update the UI is that the target Activity can be closed (or in the process of recreation) and the updating task fails. The AcyncTask class does not solve this problem. A correct solution is published at my Github workspace. But before to use this or another solution, think twice if you really need a background thread. The best way is not to use background thread at all, making all UI updates directly on the UI thread. Of course, if updates are taken from the network, then a background thread must be used.

Java Thread random output

public class Rough {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread1 testThread1 = new TestThread1();
TestThread2 testThread2 = new TestThread2();
testThread1.start();
testThread2.start();
// testThread1.stop();
System.out.println(testThread1.getName());
System.out.println(testThread2.getName());
}
}
class TestThread1 extends Thread {
public void run() {
System.out
.println("MyThread1 running :: " + System.currentTimeMillis());
}
}
class TestThread2 extends Thread {
public void run() {
System.out
.println("MyThread2 running :: " + System.currentTimeMillis());
}
}
Its giving random output each time i execute it.
Thread-0
Thread-1
MyThread1 running :: 1398752090142
MyThread2 running :: 1398752090142
next time
MyThread1 running :: 1398752090142
Thread-0
Thread-1
MyThread2 running :: 1398752090142
next time
Thread-0
MyThread1 running :: 1398752090142
Thread-1
MyThread2 running :: 1398752090142
Could anyone please explain why is it happening so?
Thanks.
It depends solely on the JVM Thread scheduler to schedule a thread. It may do it in any order when you have multiple threads. Hence you see different output.
When you start a thread, the started thread runs in parallel of all the already running threads. The thread scheduler dispatches the various threads on the available processors, and each thread gets some processor time, each in its turn. But the processor, the order and the time assigned to each thread is up to the OS thread scheduler, and you have absolutely no guarantee.
This is actually pretty expected behavior for multiple threads like this. The reason is that when you have multiple threads you can make no assumptions about the order or speed at which they run, no matter if you're running them on a multicore/threaded processor or not.
In the case that you're on a processor that only supports a single thread at a time, the order/time that threads will run is dependent entirely on how the JVM schedules your threads. Because it can schedule the threads however it wants and for as long as it wants you'll have some threads reaching their print calls earlier than others.
In the case that you're on a process that allows concurrent running of threads, you'll essentially get a race condition between various threads as to which one reaches the print statement first.

How to categorise a daemon thread to specific thread?

I have 3 threads called T1 , T2 and T3 and also i have 3 daemon threads like dt1, dt2 and dt3.
I want to (assign) provide a service dt1 to thread T1 , dt2 to thread T2 and dt3 to thread T3.
when threads T1,T2 and T3 complete their runnable task it's related daemon thread also got closed internally.
Can any one please tell me how to do it in java using thread daemon concept?
"Daemon thread" is not a concept - it's just a feature of Java threads. When a JVM is terminating, it waits for non-daemon threads to terminate by themselves. On the contrary, daemon threads just get terminated no matter what they're doing.
Leaving that behind, one idea might be to establish a "shutdown" flag inside your "daemon" thread. When the non-daemon thread terminates, it could set that flag to true. The daemon thread would check the flag and terminate once it's true. Remember to synchronize that mechanism properly, e.g. by using the volatile keyword.
So, if I understand your question correctly, you want each 'work thread' T1..T3 to have its own background thread (dt1…dt3) doing some co-processing, and you want the background thread to exit when your main thread exits, yes? You could do something like this:
Make each 'main thread T1… a Runnable that looks like this, so that when you launch your T1, it launches its own dt1, and then asks it to shutdown (via interrupt()) when it finishes.
#Override
public void run() {
ExecutorService e = Executors.newSingleThreadExecutor();
Runnable r = new Runnable() {
#Override
public void run() {
// this is your deamon thread
boolean done = false;
while (!done && !Thread.currentThread().isInterrupted()){
// Do your background deamon stuff here.
//
// Try not to use blocking, uninterruptible methods.
//
/* If you call a method that throws an interrupted exception,
* you need to catch that exception and ignore it (or set done true,)
* so the loop will terminate. If you have other exit conditions,
* just set done=true in this body */
}
}
};
e.execute(r); // launch your daemon thread
try {
// do your main stuff here
}
finally {
e.shutdownNow(); // this will 'interrupt' your daemon thread when run() exits.
}
}

How to keep my program alive for as long a daemon thread is running?

I have a requirement, that I want to start a poller once which will run foreever until the machine is restarted or the process is being killed. Now, I tried to start the poller from a main method using a shell script, but the problem is that as soon as the main method completed its execution, the poller also stoped working, as i am not using any servers to achieve so.
I heard something about daemon threads, but I am wondering how to create a daemon thread, which will run forever, and help my poller to run also.
UPDATE:
public class SomeThread extends Thread {
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
unitPoller.doPolling();
}
public static void main(String[] args) {
SomeThread someThread = new SomeThread();
someThread.setDaemon(true);
someThread.start();
}
}
Above is my updated class, now whenever I execute this thread from the main method, it creates a thread but as soon as the execution of main method completes, my poller stops working, as the JVM shuts down.
With this problem, what should i do.
Thanks
You just create a thread and call th.setDaemon(true) before calling th.start().
Edit:
The above answers the question "how to create a daemon thread", but (as the scope of the question has changed), a proper answer would be: don't create a daemon thread if you want your thread to keep the JVM from exiting once the main thread completed.
1) You need someThread.setDaemon(false) instead of 'true'. A daemon thread actualy does NOT stop java from shutting down.
From the javadoc:
void java.lang.Thread.setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be called before the thread is started.
2) I think it's not your main, but your run() method that finishes to soon. Try to put a while (true) loop around your doPolling method.
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
while (true)
unitPoller.doPolling();
}
3) It's cleaner to call join() inside the main then to rely on daemon thread behavior.
try {
someThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
4) If you need a clean way to shut down the deamonthread. Consider implementing InterruptedException to exit the polling task. You can also use the shutdown hook.
The term "daemon thread" in Java is a bit misleading, as it really means "that thread is not supposed to keep the JVM alive". This means that the JVM will shut down as soon as the last non-daemon thread terminated (as you already stated in your question).
What you are possibly looking for is the Apache Commons Daemon project, which allows to create nice "system services", started through /etc/init.d/ entries and all. This works on Windows and *nix systems.

Categories