1

I tried to experiment with threads. The question is:

What is the difference between while nested in try/catch and try/catch nested in while.

Here is the test:

    myThread.start("first");
    Thread.sleep(150);
    myThread.interrupt();

    myThread.start("second");
    Thread.sleep(250);
    myThread.interrupt();

    myThread.start("third");
    Thread.sleep(50);
    myThread.interrupt();

    myThread.start("forth");
    myThread.interrupt();

    myThread.start("fifth");
    Thread.sleep(1);
    myThread.interrupt();

I used two realisations of Thread class' run method to test console output.

first realization:

public void run() {
        while(!thread.isInterrupted()) {
            try {
                Thread.sleep(0);
                System.out.println(thread.getName());
                Thread.sleep(90);
            } catch (InterruptedException e) {
            }
        }
    }

first output

first
first
second
second
second
second
second
second
third
third
third
forth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
.....`billion of 'fifth'`
fifth

This wasn't the output I wanted, so I changed my code a little and here is second realization:

public void run() {
        try {
            while(!thread.isInterrupted()) {
                Thread.sleep(0);
                System.out.println(thread.getName());
                Thread.sleep(90);
            }
        } catch (InterruptedException e) {
        }
    }

second output:

first
first
second
second
second
third
fifth

And it's correct! I just swapped while and try. The output should be the same! Why so different?

Alesto
  • 639
  • 4
  • 13
  • 29
  • 2
    when you `catch (InterruptedException e)` you must set the interrupted flag manually if you're testing for it: http://stackoverflow.com/questions/23930189/why-does-thread-sleep-clear-the-interrupted-flag – zapl Nov 14 '15 at 11:16
  • it seems my question was unspecified. Edited. – Alesto Nov 14 '15 at 12:14

0 Answers0