Friday 20 January 2017

Java Tutorial: Java Threads (Thread yield)

MyRunnable.java
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.");
    }
}
ThreadDemo.java
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:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment