简体   繁体   中英

why is java thread not timing out

I have a java thread implementation as follows:

class MyThread extends Thread {
    private static Integer counter = 1;

    public MyThread(final String name) {
        super(name + "_" + counter);
        counter++;
    }

    @Override
    public void run() {
        try {
            sleep(0,2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.getName() + " true = " + true);
    }
}

And the main class as follows:

public class ThreadingTest {

    public static void main(String[] args) {
        MyThread thisThread = new MyThread("MyThread");
        thisThread.setDaemon(true);
        thisThread.start();
        try {
            Thread.sleep(0,1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

However even though the thread is sleeping for 2 nanoseconds and the calling thread is sleeping only for 1 nano second, why is my SOUT printing the statement?

Considering the fact that timeout of the called thread is more than the calling thread, shouldn't the calling thread be terminated before it can print the statement?

Threads that are marked as daemon will be killed when all non daemon threads are finished. Therefor your thread is simply killed. What is Daemon thread in Java?

You cannot have nanosecond precision with Thread.sleep(). Even executing those instructions will take more than a nanosecond. Try your code with miliseconds instead, and see if it works!

Method Thread.sleep determines only amount of time for which thread is sleeping (for how long thread is in the TIMED_WAITING state). After this time thread is removed from the set of waiting threads but still has to wait to obtain CPU time. And how long it will take is very nondeterministic parameter. You should never rely on time to determine exact sequence of threads execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM