Advertisement
Thread myTh= new Thread("Thread2");
In the code above, a new thread named, Thread2 is created by calling the constructor of Thread class. MyThread myth = new MyThread();
Thread t= new Thread(myth, "Thread2");
In order to create a new thread, we have passed this object of MyThread class(which has implemented Runnable interface) to the constructor of Thread class and have also passed the name of new Thread.Advertisement
class ThreadExm extends Thread //Extending the Thread class
{
ThreadExm(String name) //Constructor
{
super(name); //Calling superclass Thread's constructor
}
public void run() //Entry Point of the new thread.
{
System.out.println("Name of non-main thread - " + getName()); //Getting the name of this new thread.
try
{
System.out.println(getName()+ " is going to sleep for 3 seconds");
Thread.sleep(3000);
System.out.println(getName()+ " awakened and exits");
}
catch(InterruptedException e)
{
System.out.println(e);
}
}// run method defintion ends
public static void main(String... ar)
{
ThreadExm newTh = new ThreadExm("newThread");
newTh.start(); //starting the new thread, calls run() method automatically
}
}
Name of non-main thread - New Thread
New Thread is going to sleep for 3 seconds
New Thread awakened and exits
class ThreadRun implements Runnable
{
public void run()
{
Thread t= Thread.currentThread();
System.out.println("Name of this thread - "+ t.getName()); //Getting the name of this new thread.
try
{
System.out.println(t.getName()+ " is going to sleep for 3 seconds");
Thread.sleep(3000);
System.out.println(t.getName()+ " awakened and exits");
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
public static void main(String... ar)
{
ThreadRun newTh = new ThreadRun();
Thread th= new Thread(newThread,"New Thread"); //Calling Thread's constructor & passing the object
//of Runnable interface implementer & the name of thread.
th.start(); /starting the new thread, calls run() method automatically
}
}
Name of non-main thread - New Thread
New Thread is going to sleep for 3 seconds
New Thread awakened and exits
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement