Sunday, 11 June 2017

Java Tutorial : Java Threads (Thread names | How to set the Thread Name) ~ foundjava


Click here to watch in Youtube :

Click the below Image to Enlarge
Java Tutorial : Java Threads (Thread names | How to set the Thread Name) 
HelloThread.java
public class HelloThread extends Thread
{

    public static void main(String args[])
    {
        HelloThread helloThread = new HelloThread();
        helloThread.start();
    }

    public void run()
    {
        /*
         * Returns this thread's name.
         */
        System.out.println("Thread Name = " + this.getName());
    }

}
Output
Thread Name = Thread-0

DisplayThread.java
public class DisplayThread extends Thread
{

    public DisplayThread(String threadName)
    {
        super(threadName);
    }

    public static void main(String[] args)
    {
        DisplayThread displayThread1 = new DisplayThread("DisplayThread_100");
        displayThread1.start();
        
        DisplayThread displayThread2 = new DisplayThread("DisplayThread_200");
        displayThread2.start();

    }

    public void run()
    {
        /*
         * Returns this thread's name.
         */
        System.out.println("Run by = " + this.getName());
    }
}
Output
Run by = DisplayThread_100
Run by = DisplayThread_200

HelloRunnable.java
/*
 * public Thread(Runnable target, String name)
 * 
 * Parameters:
 * -----------
 * 
 * target - the object whose run method is invoked when
 * this thread is started. If null, this thread's run
 * method is invoked.
 * 
 * name - the name of the new thread
 */

public class HelloRunnable implements Runnable
{

    public static void main(String args[])
    {
        HelloRunnable helloRunnable = new HelloRunnable();
        Thread thread = new Thread(helloRunnable, "HelloRunnableThread");
        thread.start();
        /*
         * Returns this thread's name.
         */
        System.out.println("Thread Name = " + thread.getName());
    }

    @Override
    public void run()
    {
        System.out.println("Hello from a thread!");
    }
}
Output
Thread Name = HelloRunnableThread
Hello from a thread!

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment