What constitutes Context Switching? I know it can be by using sleep() at times. I came across an example using a combination of wait() and notify() to carry out inter-thread communication so that one thread (of Producer class) supplies a data set and then waits till the another thread (of Consumer class) has consumed it.
My question is regarding performance implication where it is argued that "CPU wastes more time doing context switching and less time doing actual work". But looking at this example I think that context switching is made to happen only when the CPU completes the desired set of operations. Then what is the logic behind above quoted statement? Please find the attached example (Courtesy: Osborne The Complete Reference Java).
/*An implementation of a producer and consumer.*/
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}