J
J
Jake Taylor2021-05-27 14:55:57
Java
Jake Taylor, 2021-05-27 14:55:57

Why isn't a thread doing what it's supposed to do in Java?

There is a LiftOff class that implements the Runnable interface . We create a subclass of SleepingTask , in which the method puts the thread into the waiting state for 9 seconds and starts all this miracle using the ExecutorService in the test method. Why is the output just like this:TimeUnit.SECONDS.sleep(9);

step: 0
step: 1
step: 2
step: 3
step: 4
status: Thread id#0 (9), 
status: Thread id#1 (9), 
status: Thread id#3 (9), 
status: Thread id#2 (9), 
status: Thread id#4 (9),


liftoff class

public class LiftOff implements Runnable {
    protected int countDown = 10;   // default
    private static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {
    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        StringBuilder msg = new StringBuilder("Thread id#").append(id)
                .append(" (").append(countDown > 0 ? countDown : "LiftOff!")
                .append("), ");

        return msg.toString();
    }

    @Override
    public void run() {
        while (countDown-- > 0) {
            System.out.println(status());
            Thread.yield();
        }
    }
}


SleepingTask class

import java.util.concurrent.TimeUnit;

public class SleepingTask extends LiftOff {
    @Override
    public void run() {
        try {
            while (countDown-- > 0) {
                System.out.println("status: " + status());
                TimeUnit.SECONDS.sleep(9);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


test run method

@Test
    public void runWithSleep() {
        ExecutorService exec = Executors.newCachedThreadPool();

        for(int i = 0; i < 5; i++) {
            System.out.println("step: " + i);
            exec.execute(new SleepingTask());
        }

        exec.shutdown();
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vamp, 2021-05-28
@n199a

This output is due to the fact that the test is considered completed immediately after exiting the runWithSleep method, after which the program is forced to terminate, despite the presence of non-daemon threads still running.
To see the full output, run the code in a non-junit context, or add an expectation to the test code:

exec.shutdown();
exec.awaitTermination(100, TimeUnit.SECONDS);

D
Dmitry Roo, 2021-05-27
@xez

We should probably wait for these 9 seconds ... you look, there will be some other conclusion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question