aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes sleep method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "sleep method" Watch "sleep method" New topic
Author

sleep method

Lalit mishra
Ranch Hand

Joined: Sep 01, 2005
Posts: 99
Thread.sleep(1000);
throws interrupted Exception
how can the thread be interrupted both programmatically and by user input ???(please give an example)
Javier Sanchez Cerrillo
Ranch Hand

Joined: Aug 02, 2006
Posts: 152
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.


SCJP 5.0 95%<br /> <br />The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.
 
Consider Paul's rocket mass heater.
 
subject: sleep method