Click here to watch in Youtube :
Click the below Image to Enlarge
![]() |
| Java Tutorial : Java Threads (Thread names | How to set the Thread Name) |
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());
}
}
OutputThread Name = Thread-0
DisplayThread.javapublic 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());
}
}
OutputRun 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!");
}
}
OutputThread Name = HelloRunnableThread
Hello from a thread!
Click the below link to download the code:

No comments:
Post a Comment