PacktPublishing / Mastering-Concurrency-Programming-with-Java-9-Second-Edition

Mastering Concurrency Programming with Java 9, Second Edition, published by Packt
MIT License
107 stars 99 forks source link

In Ch3 example2 Log System can't log #4

Open Zimang opened 7 months ago

Zimang commented 7 months ago
public class LogTask implements Runnable {

    @Override
    /**
     * Main method of the task
     */
    public void run() {
        try { 
            while (Thread.currentThread().interrupted()) {
                TimeUnit.SECONDS.sleep(10);
                Logger.writeLogs();
            }
        } catch (InterruptedException e) {
        }
        Logger.writeLogs();
    }

}

source code has a problem in the while, which makes it dosen't log. It should be

while (!Thread.currentThread().interrupted()) {
sahu-iisc commented 3 months ago

The problem with the code is that it doesn't check if the thread has been interrupted. If the thread is interrupted, the interrupted method returns true, and the loop should exit. But the code checks if the thread has been interrupted, and if it has, the loop should continue. This is a typo, and the correct code should be:

while (!Thread.currentThread().interrupted()) {

This code checks if the thread has been interrupted, and if it has, the loop exits.

Other chapter examples have similar logic(For Ex - chapter four NewsWriter,java in NewsReader), so this is probably just a typo.