Reputation: 131
I'm new to multi threading (both in general and in Java) and just trying to play around with some basic aspects of interrupted exceptions.
When I run the code below, I am getting the following output -
1: Goodbye, World! 1: Hello, World! 2: Goodbye, World! 3: Goodbye, World! 4: Goodbye, World! 5: Goodbye, World!
But I don't understand why thread 1 (the "Hello, World!") thread is stopping, since its Catch clause is empty (which I thought meant it would ignore the InterruptedException
and just finish the thread).
I'm sure I'm missing something basic, but I just don't know what it is.
Thanks for any help you can offer!
public class GreetingProducer implements Runnable
{
String greeting;
public GreetingProducer (String greetingIn)
{
greeting = greetingIn;
}
public void run()
{
try
{
for (int i = 1; i <=5; i++)
{
System.out.println(i + ": " + greeting);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
}
}
public static void main(String[] args)
{
Runnable r1 = new GreetingProducer("Hello, World!");
Runnable r2 = new GreetingProducer("Goodbye, World!");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.interrupt();
}
}
Upvotes: 0
Views: 483
Reputation: 53849
The catch
clause may be empty, but the InterruptedException
is being caught and the catch block executed.
No action is executed since the exception is swallowed, but then the code exits the try - catch
block as for any other exception.
If you had instructions in the catch
block, it will be executed.
If you want to sleep without interruption, you can use Guava's sleepUninterruptibly method:
for (int i = 1 ; i <= 5 ; i++) {
System.out.println(i + ": " + greeting);
Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
}
Then the try - catch
block becomes unnecessary.
Upvotes: 3