Share on Google+Share on Google+

Java Thread : yield() method

Ads
In this section we are going to describe yield() method with example in java thread.

Java Thread : yield() method

In this section we are going to describe yield() method with example in java thread.

yield() Method:

When you want to stop current thread and switch the CPU availability to another thread, call yield() method of Thread.

public static void yield() - This method pauses the execution of current running thread and permits the other threads to execute.

Example :This example represents the functionality of yield() method.

public class ThreadYield implements Runnable {

	Thread thread;

	public ThreadYield(String name) {
		thread = new Thread(this, name);
		thread.start();
	}

	public void run() {

		System.out.println(Thread.currentThread().getName()
				+ " is going to call yield() method...");
		Thread.yield();

		System.out.println(Thread.currentThread().getName() + " is completed.");
	}

	public static void main(String[] args) {
		new ThreadYield("Thread 1");
		new ThreadYield("Thread 2");
	}
}

Output :

Thread 1 is going to call yield() method...
Thread 2 is going to call yield() method...
Thread 1 is completed.
Thread 2 is completed.

Advertisements

Ads

Posted on: October 18, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.