• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Question about sleep method

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.

Anu
 
girl power ... turns out to be about a hundred watts. But they seriuosly don't like being connected to the grid. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic