Example
Code 1
public class ThreadStart {
public void run()
{
try
{
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
public static void main(String[] args)
{
int n = 5;
for (int i=0; i<n; i++)
{
ThreadStart object = new ThreadStart();
object.run();
}
}
}
Output
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
In this example, we have used the start() method to begin the Thread. We have printed the number of times that a thread is working.
Try it on online java compiler.
Code 2
public class StartThreads extends Thread
{
public void run()
{
System.out.println("The Thread is running...");
}
public static void main(String args[])
{
StartThreads t1=new StartThreads();
t1.run();
}
}
Output
The Thread is running…
In this example, we have started the Thread using the start() method and printed the output.
Also see, Duck Number in Java and Hashcode Method in Java
FAQs
-
How to start a thread in Java?
We can start a thread in Java by one of the two processes: Extending Thread class and implementing runnable In both cases, we override the run() functions.
-
What is the use of the start method in Java?
The Java Thread start () method is used to begin executing a thread.
-
How to start and run a thread in Java?
A thread starts its life cycle inside the run() method after creating an object of our new class and calling the start() method to start the execution of a thread.
Key Takeaways
In this article, we have covered the topic of the start() method in the Thread. We have given a brief introduction to the start() method. We also explained a Java Thread start() method and its syntax. We also took a few examples of the start() method and output. If you want to learn more about Java, please visit here Introduction To Java. We hope that this article has helped you enhance your knowledge regarding the start() method in the Thread. If you like my article, please upvote it to help ninjas grow. "Happy Coding!".