in my Java program main thread does not get interrupted. Why?
/*
* This class counts till infinity
*/
class infinityT extends Thread{
int counter = 0;
public void run(){
try{
while(true){
if(counter>500){
// this class will throw compilation error here as Thread.sleep is not a valid method here as it does not extend Thread class
Thread.sleep(1000);
}
System.out.println(counter++);
}
}catch(InterruptedException e){
System.out.println("infinity Interrupted: "+counter);
}
}
}
class interruption{
public static void main(String args[]){
Thread t = new Thread(new infinityT());
// start the thread
t.start();
try{
// main thread does not seem to interrupt
Thread.currentThread().interrupt();
Thread.sleep(2000);
}catch(InterruptedException e){
System.out.println("Main thread interrupted!");
}
t.interrupt();
}
}
Output:
...
...
499
500
infinity Interrupted: 501
Your main thread does get interrupted but what it doesn't do is sleep when you call Thread.sleep() because you've already set its interrupted flag. Hence, all or most of the numbers would get printed after the Main thread interrupted! message.
If you scroll up the console (you may have to increase its buffer or just reduce the loop count to 10 or something) you should see it getting printed as well.
As an aside, you do not need to extend Thread to call sleep() as it's a static method. Or, you can simply start infinityT directly instead of passing it as Runnable again.
main thread gets interrupted, you might have missed it among the other outputs. check carefully and if u execute the same program multiple times, see the position in which the Main thread gets interrupted
Related
I have the following code:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
ThreadImpl thr = new ThreadImpl();
thr.start();
Thread.sleep(1000);
synchronized(thr){
System.out.println( "MAIN "+thr.hashCode());
System.out.println("Main -->got the lock");
thr.wait();
System.out.println("Main -->Done with waiting");
}
}
}
class ThreadImpl extends Thread{
public synchronized void sayHello(){
System.out.println("Ssay hello ");
}
#Override
public void run() {
synchronized(this){
System.out.println( "METHOD "+this.hashCode());
System.out.println("METHOD Got the lock ");
System.out.println("METHOD Going for sleep ");
for(int i =0;i< 100000;i++);
try {
Thread.sleep(2000);
System.out.println("METHOD Woke up ");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("METHOD Done leaving the thread");
}
}
}
In the main method of ThreadDemo, I am creating a thread object ThreadImpl and starting it. Next, the main thread sleeps for 1000ms.
The run method of the thread will be executed in a separate thread.As part of this it loops 100000 times and sleeps for 2000ms. Then it exits the method.
The main thread wakes up and acquires the lock for "thr" and then goes on wait state. As the other thread has completed its execution, this wait should be forever. However, I see the following result:
METHOD 1729414014
METHOD Got the lock
METHOD Going for sleep
METHOD Woke up
METHOD Done leaving the thread
MAIN 1729414014
Main -->got the lock
Main -->Done with waiting
How is it that the main method continues its execution when no one has notified it?
This is spurious wake-up, see jls:
The thread may be removed from the wait set due to any one of the
following actions, and will resume sometime afterward:
A notify action being performed on m in which t is selected for removal from the wait set.
A notifyAll action being performed on m.
An interrupt action being performed on t.
If this is a timed wait, an internal action removing t from m's wait set that occurs after at least millisecs milliseconds plus
nanosecs nanoseconds elapse since the beginning of this wait
action.
An internal action by the implementation. Implementations are permitted, although not encouraged, to perform "spurious wake-ups", that is, to remove threads from wait sets and thus enable resumption without explicit instructions to do so.
I am working on multi threading and i got a question regard thread sleep method. when i execute sleep()(with time t1) method on already in sleeping thread(with time t2). The total sleep time is t1+t2 or t2(if t2 > t1) or t1 (if t1 > t2):
code:
my thread class:
public class SampleThread extends Thread
{
public SampleThread(String msg)
{
super(msg);
start();
}
public void run()
{
try
{
SampleThread.sleep(1000);
System.out.
println("slept for run");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.
println("extends Thread Class is exited");
}
}
my main method :
public class TestThreads {
public static void main(String[] args) {
SampleThread st = new SampleThread("Extends Thread");
some(st);
System.out.println("main thread Executed");
}
public static void some(SampleThread t2 ){
try {
t2.sleep(10000);
System.out.println("slept for some" );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
result:
slept for run
extends Thread Class is exited
slept for some
main thread Executed
from the result i can say that because sleep time for t2.sleep(10000) is more than SampleThread.sleep(1000) run() method exited first than main method.
But my question is how much time.
Sleep is called by currently running thread, it is not called on the thread object. So your sleep inside run methods pause the Sample thread, the one in the some method pauses your main thread (the one that started the program). Two different execution processes.
The sleep method is actually a static method of the Thread (and you are even calling it as such), which should already indicate for you, that it is not 'bound' to the thread object.
You cannot call sleep twice in the same thread, as to call it has to be awaked. There is no issue of additivity or priority.
So in your code, the second thread starts, executes its run method and pause for shorter time. In the meantime, the main thread continues and pauses for a long time, while the main thread sleeps the created thread finishes its sleeping and then terminates.
You have two different threads and neither blocks each other. So the one thread will wait for 10 seconds, and the other waits for 1 second. The total time you waited depends on which thread you cared about.
Your main waited 10 seconds, it doens't care if the other thread waits for 1 second or a million seconds (if the second thread is set as a daemon thread so it doesn't block the current app).
If your main app spins up a thread that is a daemon, it won't exit until all non-daemon threads are complete. In which case your main app will do its work, and then at the very last line it'll wait until those threads are done.
You can't execute sleep on a sleeping thread because sleep is a static method and can only cause the current thread to sleep.
t2.sleep(10000); causes the main thread to sleep, not t2. It's the same as Thread.sleep(10000).
I've seen a lot of example for wait and notify, but still I have a problem.
public class Main(){
public static void main(String args[]) throws Exception {
MyThread s = new MyThread();
s.start();
}
}
class MyThread extends Thread {
public void run() {
k();
}
public synchronized void k() {
System.out.println("before wait");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("do something after wait");
}
public synchronized void m() {
for (int i=0;i<6;i++)
System.out.println(i);
notify();
}
}
The only output I get when run the program is: "before wait".
The thread you create in main invokes MyThread#k() which goes into a wait. At that point, that thread will do nothing else until it is awakened or interrupted. But the only place in your code where it could possibly be awakened is the notify in MyThread#m(). Since nothing in your program calls that method, the thread can never be awoken.
What you probably want is to add a call to s.m() right after s.start() in your main program. That way your main thread will execute the notify that's needed to wake up your thread.
Unfortunately, that's very unlikely to work. The problem is that s.start() causes your created thread to become ready to run, but it doesn't necessarily run immediately. It could well happen that your call to s.m() will complete before the created thread does anything. And then you'll still have exactly the same result as before, except that you'll see the integers 0..6 printed out before before wait. The notify will do nothing, because the child thread has not yet performed its wait. (And by the way, since both MyThread#k() and MyThread#m() are both synchronized, increasing your loop limit in MyThread#m() won't change a thing... the child thread won't be able to enter MyThread#k() while MyThread#m() is running. You could improve that by putting the notify in a sycnchronized block rather than making all of MyThread#m() synchronized.)
You can try to get around this by adding Thread.sleep(1000) before s.m() in your main program. That will almost certainly work because your main thread will yield execution, giving your JVM the opportunity to schedule the child thread for some useful work. By the time the main thread wakes out of its sleep and performs its s.m() call, the child will probably have executed its wait and you will then see your do something after wait message.
But that's still pretty crummy, because it still depends on scheduling events that you don't really have any control over. There's still no guarantee that the wait will happen before the notify.
This is why when using wait/notify you should generally arrange for there to be some sort of reliable test as to whether whatever you're waiting to be done has actually occurred. This should be a condition that, once it turns turns true, will remain true at least until the test has been subsequently performed. Then your typical wait loop looks something like this:
while (!isDone()) {
synchronized(monitorObject) {
try {
monitorObject.wait();
} catch (InterruptedException e) {
}
}
}
Putting the whole thing in a loop takes care of premature waking, e.g. due to InterruptedException.
If the required work has already occurred by the time this code is executed, no wait occurs, and the notify executed by the code that did the work was a no-op. Otherwise, this code waits, and the code completing the work will eventually do a notify which will wake this code up as required. Of course, it's critical that, at the time the notify is performed, the wait condition (isDone() above) be true and remain true at least until tested.
Here's a corrected version of your code that incorporates a proper wait loop. If you comment out the Thread.sleep() call, you will likely not see the waiting message, because the work will complete before the wait loop even starts. With the sleep included, you'll probably see the waiting message. But either way, the program will work properly.
public static void main(String[] argv) throws Exception {
MyThread s = new MyThread();
s.start();
Thread.sleep(1000);
s.m();
}
class MyThread extends Thread {
#Override
public void run() {
k();
}
private boolean done = false;
public void k() {
System.out.println("before wait");
while (!done) {
System.out.println("waiting");
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
System.out.println("do something after wait");
}
public void m() {
for (int i = 0; i < 6; i++) {
System.out.println(i);
}
synchronized (this) {
done = true;
notify();
}
}
}
The problem is, that you're not calling your m method, so notify is never called, so your thread sleeps forever. You could call it in main, after the start, using s.m():
MyThread s = new MyThread();
s.start();
s.m();
Maybe you should sleep for a little time before calling the m method, as it could run sooner than k in the thread:
s.start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// nothing to do
}
s.m();
Not closely related to the question, but a throws declaration in main is not very advisable, even a generated printStackTrace is better than throwing the exception away.
I'm starting Threads in java, I would like to have a clear idea of how start()/run() acts in my situation.
I've created a thread calle t, and I've placed t.start() followed by a for cycle.
Will the for cycle be part of the thread.t or is it part of the main thread??
class Job implements Runnable{
Thread t;
Job(String tName){
t=new Thread(this, tName);
System.out.println("This is thread: "+t.getName());
t.start();
System.out.println("This is the end of constructor");
try{ /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
for(int i=0;i<5;i++){
System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
}
public void run(){
System.out.println("This is the start of RUN()");
try{
for(int i=0;i<5;i++){
System.out.println("This is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
finally{
System.out.println("Fnally block reached: "+t.getName());
}
}
}
I would like to have a clear idea of how start()/run() acts in my situation
start() method spawns a new thread of execution and executes the run method in that thread. In this case , the thread will have its own call stack. Whereas, calling run() method directly doesn't spawns a new thread. Instead this will cause the run() method to execute in the current executing thread having old call stack.
Will the for cycle be part of the thread.t or is it part of the main thread??
The for cycle will be part of the Thread(in your case is main thread if you create Job instance in main thread) from which Thread t is spawned. And if you want to confirm then simply print the name of thread which is executing that for loop using Thread.currentThread().getName() . Example:
try{ /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
System.out.println(Thread.currentThread().getName()+" is executing this for loop");
for(int i=0;i<5;i++){
System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
The method t.start() and the following try/for code are executed in the same thread. This is the main thread if you called the Job(String) constructor from the main thread.
The run() method is executed in the new thread.
Will the for cycle be part of the thread.t or is it part of the main thread??
The main thread. When a thread is forked, the new Thread just calls the run() method. In your case, the main thread calls start() and then continues to run the for() method. This actually will most likely be called before the new thread is finished starting. The new thread that is forked only calls the run() method and any other methods used by run().
FYI, it is considered very bad practice to start a thread from within an object constructor. This "leaks" references to the current object while it is still being initialized. You should consider adding a start() method onto the Job or call start() after the Job constructor has finished.
Job job = new Job(...);
job.start();
Also, since the main thread is the one running your for loop, it will throw InterruptedException only if the main thread gets interrupted -- not the Job thread.
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
According to java when setDaemon is set to true
it does not prevent the JVM from
exiting when the program finishes but
the thread is still running. An
example for a daemon thread is the
garbage collection.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true, actually it should keep on running . when setDaemon is set false the child thread print value of i even though main thread exited.
kindly clarify my doubt.
public class DeamonSample implements Runnable
{
public void run()
{
try
{
System.out.println("T1 started...");
for (int i=0;i<1000;i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.print(i+" ");
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
System.out.println("T1 ended...");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Main Started...");
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
DeamonSample deamonSample=new DeamonSample();
Thread t1=new Thread(deamonSample);
t1.setDaemon(true);
t1.start();
System.out.println("T1 Type="+t1.isDaemon());
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
System.out.println("Main ended...");
}
}
By default threads are not daemon threads. If you get to the end of your main with any thread that's not a daemon then the process will keep running. By calling setDaemon(true) you're telling the JVM that your thread shouldn't block shutdown at the end of main.
The DeamonSample instance is assuredly not stopped when t1.setDaemon(true); is executed; the nondeterminism that you see comes from the prints. Characters are written to thread-local buffers before they are merged into a single stream.
Here's a bit of code to illustrate. Two threads take turns incrementing a counter and printing its state, but the numbers you see may be very much out of order.
import java.util.concurrent.atomic.AtomicInteger;
public class FunnyPrinter extends Thread {
static AtomicInteger counter = new AtomicInteger(0);
int parity;
public FunnyPrinter(int parity) {
super();
this.parity = parity;
}
public void run() {
for (;;)
if (counter.intValue() % 2 == parity)
System.out.println(counter.incrementAndGet());
}
public static void main(String[] args) {
FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
t1.start(); t2.start();
}
}
If you need determinism, synchronize on System.out and flush it before the end of the block.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true
This will not happen. Check your output again. Your output will contain the following lines:
Main Started...
Main Thread Type=false
T1 Type=true
Main Thread Type=false
Main ended...
..actually it should keep on running .
Being a daemon thread, it wont. Since all non-daemon threads (main) have finished, the jvm will exit.
when setDaemon is set false the child thread print value of i even though main thread exited. kindly clarify my doubt.
Correct
The main-thread terminates, before your daemon-thread can print out all your numbers...
if your new thread isDaemon = true, try this line after starting the thread ():
...
Thread t1=new Thread(deamonSample);
try{
t1.join();
}catch(InterruptedException ie){
ie.printStackTrace();
}
...
you will see, the daemon-thread will come to an end... (at least, that wouldn´t be multithreading anymore, but that example is for clarifying purpose only)