View Single Post
  #1 (permalink)  
Old 05-05-2008, 06:22 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Age: 26
Posts: 6,005
Last Blog:
SAP, ERP and EDI
Rep Power: 20
Jordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud of
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Tutorial: Java Threads

Java Threads

In this tutorial I will explain what threads are and how to use them.

Description
Simply put a thread is an instance of the class java.lang.Thread.


Creating a thread
There are two ways to create a thread.
  • Extend the the Thread Class and override its method
  • Implement the runnable interface and implement its run method.
We will see how to implement the interface in a step by step fashion


Implementing a thread by extending the thread interface
Making a runnable object


Code:
Runnable r =  new MyClasToRun();
Runnable is an interface. It is extended by the class whose thread you need to create and run. So what you are doing here is making a reference of the interface implemented to point to an object of the class which implements the interface. A basic Java concept.

Now its time to send the reference [/i]r [/i]to a thread so
that it can run it.

Code:
Thread t = new Thread(r);   //Consider this for the example, the others are just to give you the various  flavors possible.
     Thread t = new Thread();
    Thread t = new Thread(Runnable  object, String name);
     Thread t = new Thread(String  Name);
This shows the various constructors that are present. You can even give a name to the thread or simply create an empty thread and then send it object when needed. It all depends on your requirements.

Now its time to start the thread you have created. All you do is simply call the start method of the Thread Class.

Code:
t.start();
But what does it start? Which method does it run? It simply runs the run method. Isn't that obvious, you run the run method!

Code:
public void run()
     {
        //Do stuff here
     }
What if you want to put the thread to rest for some time. What do you do? Well you put it to sleep by calling the sleep method! It sleeps for 1000 millisecond for the code given below. (1 second = 1000 millisecond)

Code:
t.sleep(1000);
To sum it up, here is the entire flow : NEW ------> RUNNABLE ------> RUNNING

But now the question arises, what is the big thing about having a thread instead of simple class.

The first thing is, that the overhead involved for the JVM is less for starting a new Thread compared to a new process.

Second is, in case you put a thread to sleep, the resources are freed and other threads can use it.
So what you have is a time sharing system that splits the time between various threads and you get maximum possible output.
The example below will explain to you fully have things work in the world of threads.

Code:
class DoAllWork implements Runnable
{
    public void run()
    {
        for(int i=0; i<5 ;i++)
        {
            System.out.println(i+" Running thread : "+Thread.currentThread().getName());
            try
            { 
                Thread.sleep(1000);//Puts the thread to sleep for 1 second.
            }
            catch (InterruptedException e) {
                   e.printStackTrace();
            }}}}

public class ThreadsEx {
    public static void main(String[] args) {
        Runnable doWork = new DoAllWork(); //Create a reference to the to the  DoAllWork class.
        Thread t1 = new Thread(doWork,"The first");
        Thread t2 = new Thread(doWork,"The second");
        t1.start();
        t2.start();
    }}
Code:
Output
0 Running thread : The first
0 Running thread : The second
1 Running thread : The first
1 Running thread : The second
2 Running thread : The first
2 Running thread : The second
3 Running thread : The first
3 Running thread : The second
4 Running thread : The first
4 Running thread : The second
Explanation:
  • You began with creating a Runnable reference which points to the object of the class which implements the run method.
  • Then you create thread and pass that reference and the name to the constructor.
  • Now its time to start the two threads, for that you used t.start().
  • Once the start method is called, the run method of the object which was passed to the thread is called. And that was what happened.
  • Run got called and so the first line got printed of thread "The first". - After that the thread was put to sleep using Thread.sleep(1000). This made thread one go to sleep for one second.
  • Meanwhile thread 2 which was theorotically started on the same instance came along, printed its line and was put to sleep.
  • Now here is the tricky part, both the threads are in theory put to sleep at the same time for the same duration. So which one wakes up first is for the JVM to decide.
  • The sequece after the first two outputs may change depending on the whims and wishes of the JVM.

__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
Don't hesitate to ask any questions that you have! Check out our ASCII Calculator!
Reply With Quote

Sponsored Links