wait executing block of code for thread dies - java

all i want block of code wait for another thread to die
where this thread not event thread

I believe this is what Thread.join() method is for:
public final void join() throws InterruptedException
Waits for this thread to die.

From what I've been able to understand, it looks like you want a block of code to be executed after some thread dies, but you don't want Thread.join() to block the current thread? Then execute the whole thing in a yet another thread:
new Thread() {
public void run() {
someThread.join(); // someThread is the thread that you're waiting to die
// your block of code
}
}.start();
This will execute the code after someThread dies, but won't suspend the current thread.

java.util.concurrent.CountDownLatch can be used here.

Related

How does a thread move from running to runnable state?

I want to know how and when does a Thread move back and forth between runnable and running states.What actually happens behind the scenes.I guess this will be needed in case of ThreadPool but I am not able to understand entirely.Please help me to understand this.
if thread is in running state that means its executing run() method and when its in runnable method its executing start() method....so I guess moving from running to runnable means its going back from run() to start()
In the nomenclature of most operating systems, "running" means that the thread actually is executing instructions on some CPU, and "runnable" means that nothing prevents the thread from "running" except the availability of a CPU to run on.
A Java program can not tell the difference between those two states. The thread states that Java knows about are NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
A thread is NEW before t.start() is called, and it can never go back to NEW afterward. WAITING and TIMED_WAITING both mean that the thread is waiting for a notify() call in some other thread. BLOCKED means it is waiting for anything else (e.g., to enter a synchronized block), and TERMINATED means it's finished.
Yield is a static method that tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.
There is no guarantee that Yield will make the currently executing thread to runnable state immediately. Remember an important point that yield method does not make the thread to go to Wait or Blocked state. It can only make a thread from Running State to Runnable State.
Extract from A Programmer's Guide to Java SCJP Certification: Threads:
static void yield()
This method causes the current thread to temporarily pause its execution and, thereby, allow other threads to execute. It is up to the JVM to decide if and when this transition will take place.
static void sleep (long millisec) throws InterruptedException
The current thread sleeps for the specified time before it becomes eligible for running again.
final void join() throws InterruptedException
final void join(long millisec) throws InterruptedException
A call to any of these two methods invoked on a thread will wait and not return until either the thread has completed or it is timed out after the specified time, respectively.
void interrupt()
The method interrupts the thread on which it is invoked. In the Waiting-for-notification, Sleeping, or Blocked-for-join-completion states, the thread will receive an InterruptedException.
Below Example illustrates transitions between thread states. A thread at (1) sleeps a little at (2) and then does some computation in a loop at (3), after which the thread terminates. The main() method monitors the thread in a loop at (4), printing the thread state returned by the getState() method. The output shows that the thread goes through the RUNNABLE state when the run() method starts to execute and then transits to the TIMED_WAITING state to sleep. On waking up, it computes the loop in the RUNNABLE state, and transits to the TERMINATED state when the run() method finishes.
Example :Thread States
public class ThreadStates {
private static Thread t1 = new Thread("T1") { // (1)
public void run() {
try {
sleep(2); // (2)
for(int i = 10000; i > 0; i--); // (3)
} catch (InterruptedException ie){
ie.printStackTrace();
}
}
};
public static void main(String[] args) {
t1.start();
while(true) { // (4)
Thread.State state = t1.getState();
System.out.println(state);
if (state == Thread.State.TERMINATED) break;
}
}
}
Possible output from the program:
RUNNABLE
TIMED_WAITING
...
TIMED_WAITING
RUNNABLE
...
RUNNABLE
TERMINATED

Awake thread from sleep

I am creating an program and working with threads in details for the first time and stuck into an situation .Please help me in that.
I am having a thread which is in wait state.Now at some instance I want to kill or to awake thread and resume from another class .For this I am saving object of thread .I don't know how to do this .I tried to notify thread but got exception.Here is my code:
Class one:
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(VariableClass.THREAD_WAIT_SECONDS);
if(message !=null)
message_status = message.getStatus();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//do other stuff and save the thread object
VariableClass.threads.remove(message.getUniqueId());
}
});
t.start();
VariableClass.threads.put(pojo.getUniqueId(),t);
Class two:
Thread t =VariableClass.threads.get(tempId);
t.notify();
I just want to resume or kill thread.
If your thread t is sleeping, calling t.interrupt() will cause an InterruptedException to be thrown from the line calling Thread#sleep. It will get caught in your catch block and your thread will proceed from there to do its cleanup and exit.
If there was an issue where your thread was not sleeping or waiting but still wanted to be aware of whether it was interrupted, the code in your Runnable could check the interrupted flag on the current thread. Remember that the interrupted flag gets reset once an InterruptedException is thrown.
Wait and notify are for threads that are synchronizing on a monitor, that's not applicable to your example. Threads wait on a monitor and receive notifications, but the notifications are not made to a specific thread; for Object#notify, some thread waiting on that monitor gets chosen but the thread calling notify has no control over which one is picked.
Here's an example of using interrupt to wake a thread from sleeping.
Your thread is sleeping for the specified amount of time. Call interrupt on it, if you just want to "kill it" and you don't care too much what will happen with it later. You cannot simply "awake it" from another thread, if it's sleeping it has to sleep as much as it has been told to. Calling notify has nothing to do with this situation (there's no prior wait call). Even if did, you're calling it incorrectly.
You do not use notify in this case. I suggest reading the JavaDoc on #wait/#notify/#notifyAll
You use #notify and #notifyAll to create a framework with concurrency such as a Thread that does work on an instance of a certain object and other threads are waiting to work on it.
A thread "dies" out if the run function is over, but if you want to stop the thread immediately, use #interrupt.

How a sleeping thread can send interrupt to itself?

I am reading Java Threads. I am looking into sleep() method. The books states that
When a thread encounters a sleep call, it must go to sleep for
specified amount of time, unless it is interrupted before its wake-up
time.
I am reading about interrupts, but how can a thread send interrupt to itself? I think so
another thread can send interrupt? Am i understanding correct? Additionally, do both of
the threads, one which will send the interrupt should be having same target Runnable? If
for suppose a thread is interrupted, does it go back to Runnable state? I am really sorry,
if i am sounding stupid, it's just pretty new for me. Thanks
A Thread can't interrupt itself while sleeping, because it is... sleeping.
A picture is worth a thousand words so here is a simple example where a thread starts sleeping and the main thread interrupts it:
public static void main(String[] args) throws Exception {
Runnable sleeper = new Runnable() {
public void run() {
try {
System.out.println("sleeper is going to sleep");
Thread.sleep(1000);
System.out.println("sleeper is awake");
} catch (InterruptedException e) {
System.out.println("sleeper got interrupted");
}
}
};
Thread t = new Thread(sleeper);
t.start(); //run sleeper in its own thread
Thread.sleep(500); //sleeping in main a little to make sure t is started
t.interrupt();
}
which prints:
sleeper is going to sleep
sleeper got interrupted
As for the main question - Sleeping thread cannot interrupt itself because it sleeps, BUT any other thread can try to iterrupt the sleeping one. Here you have doc explaining threads and thread lifecycle.
Yes, only another thread can send an interrupt to a sleeping thread. It is not possible for a thread to send interrupt to itself(Simply contrast it to real life, if a person is sleeping then to wake him, we require some other person). And yes, after interrupting a thread goes back to Runnable state.
As far as I know its another thread which causes the interrupt. So when a thread calls sleep for certain time, Java Runtime makes a note of this, and when time has passed, it causes the interrupt which wakes up the sleeping thread.
According to Thread#interrupt
Thread can interrupt itself.It is always possible.
Example is :
public static void main(String[] args) throws ParseException, InterruptedException {
Thread.currentThread().interrupt();
try{
Thread.currentThread().sleep(200);
}catch(InterruptedException ie){
System.out.println("Current thread is interrupted");
}
}
invoking interrupt never throws exception.It set the interrupt status flag.
When this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
or

Who notifies the Thread when it finishes?

I have one question regarding wait/notify based threads interaction.
The output of the below code is Im. How output can be Im as there is no other thread calling notify() on Thread object. Is it like JVM implicitly calls notify() in above such scenarios where you try to wait on Thread class instance.
A thread operation gets stuck when it waits without receiving any notification. Now what if I wait on Thread class instance wait(). For e.g.
public class WaitingThread {
public static void main(String[] args) {
Thread t1 = new Thread();
t1.start();
synchronized (t1) {
try {
t1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Im");
}
}
Your program is leaving wait() because the thread is finishing immediately. This is a byproduct of the Thread library that the Thread object is notified when the thread finishes. This is how join() works but it is not behavior that should be relied on since it is internal to the thread sub-system.
If you are trying to wait for the thread to finish then you should be using the t1.join() method instead.
Your thread is finishing immediately because it does not have a run() method defined so it is started and finishes. Really it is a race condition and the thread that is started could finish before the main thread gets to the wait() method call. You can see this if you put a short sleep (maybe 10ms) after the start() is called. Then you can see that you program will sit in wait() forever.

How to suspend thread using thread's id?

Code which I am trying
public void killJob(String thread_id)throws RemoteException{
Thread t1 = new Thread(a);
t1.suspend();
}
How can we suspend/pause thread based on its id?
Thread.suspend is deprecated,There must be some alternative to achieve this.
I have thread id I want to suspend and kill the thread.
Edit: I used this.
AcQueryExecutor a=new AcQueryExecutor(thread_id_id);
Thread t1 = new Thread(a);
t1.interrupt();
while (t1.isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
t1.interrupt();
return;
}
}
But I am not able to stop this thread.
How can we suspend/pause thread based on its id? ... I have thread id I want to suspend and kill the thread.
The right way to kill a thread these days is to interrupt() it. That sets the Thread.isInterrupted() to true and causes wait(), sleep(), and a couple other methods to throw InterruptedException.
Inside of your thread code, you should be doing something like the following which checks to make sure that it has not been interrupted.
// run our thread while we have not been interrupted
while (!Thread.currentThread().isInterrupted()) {
// do your thread processing code ...
}
Here's an example of how to handle interrupted exception inside of a thread:
try {
Thread.sleep(...);
} catch (InterruptedException e) {
// always good practice because throwing the exception clears the flag
Thread.currentThread().interrupt();
// most likely we should stop the thread if we are interrupted
return;
}
The right way to suspend a thread is a bit harder. You could set some sort of volatile boolean suspended flag for the thread that it would pay attention to. You could also use object.wait() to suspend a thread and then object.notify() to start it running again.
I posted a PauseableThread implementation recently that uses a ReadWriteLock internally. Use one of these or a variant and you should be able to pause your threads.
As to pausing them by id, a little googling suggests a way to iterate over all threads which looks like it should work. Thread has exposed a getId method for some time.
Killing the thread is different. #Gray has neatly covered that one.

Categories

Resources