schedule threads in java programming
Java defines methods wait, notify, and notifyAll in the base class Object. The method wait is used when a thread is waiting for some condition that is typically controlled by another thread. It allows us to put a thread to sleep while waiting for the condition to change, and the thread will be wakened up when a notify or notifyAll occurs. Therefore, wait provides a method to synchronize activities between threads, and it is applicable to solve this problem.
A solution based on methods wait and notify is found in Listing 2-19. Listing 2-19. Java code to schedule threads
}
Java defines methods wait, notify, and notifyAll in the base class Object. The method wait is used when a thread is waiting for some condition that is typically controlled by another thread. It allows us to put a thread to sleep while waiting for the condition to change, and the thread will be wakened up when a notify or notifyAll occurs. Therefore, wait provides a method to synchronize activities between threads, and it is applicable to solve this problem.
A solution based on methods wait and notify is found in Listing 2-19. Listing 2-19. Java code to schedule threads
public class SimpleThread extends Thread {
private int value;
public SimpleThread(int num) {
this.value = num;
start(); } public void run() { while(true) {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.print(value + " ");
}
}
}
}
public class Scheduler {
static final int COUNT = 3;
static final int SLEEP = 37;
public static void main(String args[]) {
SimpleThread threads[] = new SimpleThread[COUNT];
for(int i = 0; i < COUNT; ++i)
threads[i] = new SimpleThread(i + 1);
int index = 0;
while(true){
synchronized(threads[index]) {
threads[index].notify();
}
try {
Thread.sleep(SLEEP);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
index = (++index) % COUNT;
}
}
}
There are four threads in the code above. The first is the main thread in the Java application, which acts as the scheduler, and it creates three printing threads and stores them into an array. The main thread awakens threads one by one according to their index in the array via the method notify. Once a thread wakes up, it prints a number and then sleeps again to wait for another notification. Source Code: 004_Scheduler.java
www.cinterviews.com appreciates your contribution please mail us the questions
you have to cinterviews.blogspot.com@gmail.com so that it will be useful
to our job search community
No comments:
Post a Comment