In the previous tutorials about Threads we have learnt about the basics of Threads,How to create a Thread and also how to start a Thread. So far we have learnt how to start a single Thread but in this tutorial we will learn about how we can start and run Multiple Threads
To start Multiple Threads we use Runnable interface method which is best one. So we will implement the Runnable interface in our class and use the instance of our class to start Threads. To start a Thread we simply need a method start() to begin all the Threads.
Consider following example it will help you understand the Multiple Threads:-
class MultiTest implements Runnable
{
public void run()
{
for(int i=0;i<3;i++)
System. out. println(“Run by ” + Thread. currentThread(). getName());
}
}
public class ManyThreads
{
public static void main(String a[])
{
MultiTest mt = new MultiTest();
Thread b = new Thread(mt);
Thread c = new Thread(mt);
c. setName(“Programmer”);
b. setName(“Designer”);
c. start();
b. start();
}
}
Output:- When we executed the program with loop running 3 times then we got the output
Run by Programmer
Run by Programmer
Run by Programmer
Run by Designer
Run by Designer
Run by Designer
but when we made loop to run for 100 times then it gave the output as
Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
Run by Designer
Run by Programmer
. . . . . .
Well Friends one thing you need to know that you can never be certain of the output when many Threads are in operation. The bottomline is that the behaviour cannot be predicted and are also not guaranteed when multiple Threads are in execution.
You must know that every Thread will start and come to finish but the order in which they begin execution is not always the order in the program. In the last example program you might not be able to figure it out but when you run the loop for a Thousand times then it will be clear that any order can be followed you can never be certain of the output.
Topics: Java, Web Development
Submit Your Article





