Sunday 15 June 2014

Using yield() and join() in threading in java

Use of yield() : yield() is used in threading to allow another thread to execute which have same priority and itself switch running to runnable state.

Example :

package mypkg;

public class YieldDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread p = new Producer();
Thread c = new Consumer();
p.setPriority(Thread.MIN_PRIORITY);
c.setPriority(Thread.MAX_PRIORITY);
p.start();
c.start();
}
}

class Producer extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am producer :" + i);
Thread.yield();
}
}
}

class Consumer extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {

System.out.println("I am consumer :" + i);
Thread.yield();
}
}


}


Use of join() : This method is used to current thread execute completely without any intrrupt. When it execute completely then control give other thread for execution.

Example :

No comments:

Post a Comment