0

Good day - I am learning concurrency in Java and wrote the following code to test interrupting a thread. If the while loop in thread t2 prints out a message as in the code below, everything works as expected: thread t1 counts up to 1_000, then gets interrupted. If the same while loop is just while(aCounter.getCount() < 1_000); t1 never stops. All of this, in run mode (Apache Netbeans 12.4); in debug mode, if I placed a breakpoint where t2 requests t1 to interrupt and hit "continue" after hitting the breakpoint, both ways work (although with a higher final count, I imagine because of the time spent halted in breakpoint). I did follow t1.interrupt() execution (that is, in Thread.java) in both cases and found no differences Any ideas? Thanks.

class Counter { private int ct = 0;

public void incrementCount() {
    ct++;
}

public int getCount() {
    return ct;
}    

}

public class ThreadsApp { public static void main(String[] args) {

    Counter aCounter = new Counter();

    /**
     * Prints out and increments the value of the counter until interrupted by t2
     */
    Thread t1 = new Thread( () -> {
       
        while(!Thread.currentThread().isInterrupted()) {
            System.out.println(aCounter.getCount());
            
            aCounter.incrementCount();
        }
        
        if(Thread.currentThread().isInterrupted()) System.out.println("Thread t1 interrupted.");
    });
    
    /**
     * When the counter value is greater than 1_000, sends an interrupt request to t1
     */
    Thread t2 = new Thread( () -> {

        while(aCounter.getCount() < 1_000)
        {
            System.out.println("Thread t2 running...");
        }

        System.out.println("Sending to thread t1 an interrupt request...");
        t1.interrupt();            
    });       

    t1.start();
    
    t2.start();        
    
    while(t1.isAlive());
}

}

0 Answers0