wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question about sleep method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question about sleep method" Watch "Thread Question about sleep method" New topic
Author

Thread Question about sleep method

Anu Bhagat
Ranch Hand

Joined: Jun 20, 2008
Posts: 64
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


SCJP5.0, SCJA
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Anu Bhagat
Ranch Hand

Joined: Jun 20, 2008
Posts: 64
Thanks.

Anu
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Question about sleep method
 
Similar Threads
Threads blocking on static method.... or do they?
Lock Mechanism Doubt
Practice question on synchronized
Thread Question??
Another Whizlabs Question...