| 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
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
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
|
 |
 |
|
|
subject: Thread Question about sleep method
|
|
|