Wednesday, 5 October 2016

Java Code Showing Use of Thead Yield Method ?

This blog is all about to learn Core Java Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Here we learn the use of Yield Method of Thread Class.

public static void yield()
Yield method belongs to Thread Class.And thread class belongs to java.lang.* package.
Yield Method stops the current running thread and allows another thread to execute.

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

class consumer extends Thread{
public void run(){
 for(int i=0;i<2;i++){
 System.out.println("consumer "+i);
 Thread.yield();
 }
}
}
public class YieldMethod {
public static void main(String[] args) {
Thread p=new producer();
Thread c=new consumer(); 
p.start();
c.start();
}

}

Program Output :-

Producer 0
consumer 0
Producer 1

consumer 1


No comments:

Post a Comment