Tuesday, December 8, 2009

Starting and running Multiple Threads

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.

Suggested Reading:-

Java Thread Basics
Java Thread life cycle
Ways of Thread creation
How to Start Java Thread
Main Thread creation and Handling

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP