This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sleep method

 
Lalit mishra
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • 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)
 
Javier Sanchez Cerrillo
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic