Threads
Manipulate threads
Put a thread to sleep
A version of the Count Down application that uses sleep() rather than yield()
public class CountDownSleepApp { public static void main(String[] args) { Thread count1 = new CountDownEven(); // instantiate countdown threads Thread count2 = new CountDownOdd(); count1.start(); // start the countdown threads count2.start(); } } class CountDownEven extends Thread // this class counts even numbers { public void run() { for (int i = 10; i > 0; i-= 2) { System.out.println(this.getName() + " Count " + i); try { Thread.sleep(500); // sleep for 1/2 second } catch (InterruptedException e) {} // ignore any interruptions } } } class CountDownOdd extends Thread // this class counts odd numbers { public void run() { for (int i = 9; i > 0; i-= 2) { System.out.println(this.getName() + " Count " + i); try { Thread.sleep(2000); // sleep for 2 seconds } catch (InterruptedException e) {} // ignore any interruptions } } }
Console output from the Count Down application that puts a thread to sleep
Thread-0 Count 10 Thread-1 Count 9 Thread-0 Count 8 Thread-0 Count 6 Thread-0 Count 4 Thread-1 Count 7 Thread-0 Count 2 Thread-1 Count 5 Thread-1 Count 3 Thread-1 Count 1 Press any key to continue . . .