• 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

sleep method

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thread.sleep(1000);
throws interrupted Exception
how can the thread be interrupted both programmatically and by user input ???(please give an example)
 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Javier {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {

/* An infinite loop that attemps to display a message every
* two seconds (this is not a warranty) */
while (true) {
try {
System.out.println("Hi this Child Thread: Hello every two seconds");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
e.getMessage();
}

}

}
});

t.start();



/* An infinite loope that attemps to display a message every half a
* second (this is also not a warranty) */
while (true) {
try {
System.out.println("Hi this is Father Thread: Hello every half second");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
e.getMessage();
}
}


//This is never reachead unless there's an exception



}
}


In the previous code I've created two threads. The one invoked by the JVM and a child Thread.

The Main Thread creates another child that will attemp to display a message every two seconds. And the Main Thread itself go to sleep every half a second and once is in the state of "runnable" It will display the message.

Interrupting Threads by user input requieres more code and can be done via a Graphical User Interface.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic