Lost Password?

  #1 (permalink)  
Old 05-05-2008, 06:22 PM
Jordan's Avatar   
Jordan Jordan is online now
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Age: 25
Posts: 4,514
Last Blog:
Zend: PHP Security Web...
Rep Power: 50
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 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
Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 05-17-2008, 10:37 AM
Turk4n's Avatar   
Turk4n Turk4n is offline
Programmer
 
Join Date: May 2008
Location: ?
Age: 18
Posts: 106
Rep Power: 3
Turk4n has a spectacular aura aboutTurk4n has a spectacular aura aboutTurk4n has a spectacular aura about
Send a message via MSN to Turk4n Send a message via Skype™ to Turk4n
Default Re: Tutorial: Java Threads

Great Tutorial !
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Tags
threads



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Tutorial: Starting Java Using Netbeans Jordan Java Tutorials 0 04-05-2008 02:45 PM
Java tutorial : my sql with java Arkie Java Tutorials 2 04-05-2008 12:51 PM
threads in java stasik Java Help 2 03-13-2007 03:34 PM
John's Java Tutorial Index John Java Tutorials 0 01-11-2007 03:05 PM


All times are GMT -5. The time now is 10:02 PM.

Contest Stats

John ........ 87.50000
dargueta ........ 75.00000
Xav ........ 50.00000
MeTh0Dz ........ 20.00000
gaylo565 ........ 18.00000
Johnnyboy ........ 3.00000

Contest Rules

Ads