Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Question about sleep method

 
Anu Bhagat
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

I am confused about sleep method of Java Threads.

I understand that Threads sleep method throws checked exception, so sleep() must be wraped in a try/catch block, or declare to throw it.

The following code works, but it seems to be violating the rule. please explain.


[b]class MyRunnable implements Runnable
{
String[] s;
public MyRunnable(String[] s)
{
this.s = s;
}
public void run()
{
synchronized (this)
{
System.out.print(s[0] + s[1] + s[2]);
}
}
}
class Test
{
public static void main (String[] args) throws Exception
{
String[] s = new String[]{"1","2","3"};
MyRunnable myRunnable=new MyRunnable(s);
Thread t1 = new Thread(myRunnable);
synchronized(myRunnable)
{
t1.start();
Thread.sleep(4000);
s[0] = "A";
s[1] = "B";
s[2] = "C";
}
}
}

The above code workks. But why? Shoudn't it complain about sleep not wraped in try/catch
Thanks in advance.
Anu
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anu Bhagat wrote:Hello.
I understand that Threads sleep method throws checked exception, so sleep() must be wraped in a try/catch block, or declare to throw it.



You yourself gave the answer. The main method throws Exception and InterruptedException thrown by sleep method is a sub-class of Exception class...
 
Anu Bhagat
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

Anu
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic