Click here to watch in Youtube :
https://www.youtube.com/watch?v=4ZgZOGWUik8&list=UUhwKlOVR041tngjerWxVccw
public class MyRunnable implements Runnable { Thread t; public MyRunnable(String str) { t = new Thread(this, str); // this will call run() function t.start(); } public void run() { for (int i = 0; i < 5; i++) { /* * Yields control to another thread every 5 * iterations */ if ((i % 5) == 0) { System.out.println(Thread.currentThread().getName() + " yielding control..."); /* * Causes the currently executing thread * object to temporarily pause and allow * other threads to execute. * * A hint to the scheduler that the current * thread is willing to yield its current * use of a processor. The scheduler is free * to ignore this hint. */ Thread.yield(); } } System.out.println(Thread.currentThread().getName() + " has finished executing."); } }
public class ThreadDemo { public static void main(String args[]) throws InterruptedException { new MyRunnable("Thread 1"); new MyRunnable("Thread 2"); new MyRunnable("Thread 3"); } }Output
Thread 1 yielding control... Thread 1 has finished executing. Thread 2 yielding control... Thread 3 yielding control... Thread 3 has finished executing. Thread 2 has finished executing.Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_yield_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_yield_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/4a03b5014bb513b61dfa414428ea9747b1421899/BasicJava/ThreadDemo_yield_App/?at=master
See also:
No comments:
Post a Comment