Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Introduction to Java threads

A quick tutorial on how to implement threads in Java

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 3

In this case, the CounterThread class was forced to implement Runnable since it extended the class Applet. As in all applets, the init() method gets executed first. In init(), the variable Count is initialized to zero and a new instance of the Thread class is created. By passing this to the Thread constructor, the new thread will know which object to run. In this case this is a reference to CounterThread. After the thread is created it needs to be started. The call to start() will call the target's run() method, which is CounterThread.run(). The call to start() will return right away and the thread will start executing at the same time. Note that the run() method is an infinite loop. It is infinite because once the run() method exits, the thread stops executing. The run() method will increment the variable Count, sleep for 10 milliseconds and send a request to refresh the applet's display.

Note that it is important to sleep somewhere in a thread. If not, the thread will consume all CPU time for the process and will not allow any other methods such as threads to be executed. Another way to cease the execution of a thread is to call the stop() method. In this example, the thread stops when the mouse is pressed while the cursor is in the applet. Depending on the speed of the computer the applet runs on, not every number will be displayed, because the incrementing is done independent of the painting of the applet. The applet can not be refreshed at every request, so the OS will queue the requests and successive refresh requests will be satisfied with one refresh. While the refreshes are queuing up, the Count is still being incremented but not displayed.

Suspending and resuming

Once a thread is stopped, it cannot be restarted with the start() command, since stop() will terminate the execution of a thread. Instead you can pause the execution of a thread with the sleep() method. The thread will sleep for a certain period of time and then begin executing when the time limit is reached. But, this is not ideal if the thread needs to be started when a certain event occurs. In this case, the suspend() method allows a thread to temporarily cease executing and the resume() method allows the suspended thread to start again. The following applet shows the above example modified to suspend and resume the applet.

public class CounterThread2 extends Applet implements Runnable
{      
        Thread t;       
        int Count;
        boolean suspended;
        public boolean mouseDown(Event e,int x, int y)
        {      
                if(suspended)
                        t.resume();
                else
                        t.suspend();
                suspended = !suspended;
                return true;
        }
        ...
}


CounterThread2 Example and Source code

To keep track of the current state of the applet, the boolean variable suspended is used. Distinguishing the different states of an applet is important because some methods will throw exceptions if they are called while in the wrong state. For example, if the applet has been started and stopped, executing the start() method will throw an IllegalThreadStateException exception.

Scheduling

Java has a Thread Scheduler that monitors all running threads in all programs and decides which threads should be running and which are in line to be executed. There are two characteristics of a thread that the scheduler identifies in its decision process. One, the most important, is the priority of the thread, the other is the daemon flag. The scheduler's basic rule is if there are only daemon threads running, the Java Virtual Machine (JVM) will exit. New threads inherit the priority and daemon flag from the thread that created it. The scheduler determines which thread should be executed by analyzing the priorities of all threads. Those with the highest priority are allowed execution before any lower priority threads.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (17)
Login
Forgot your account info?

Java threads referenceBy Anonymous on November 14, 2009, 5:35 amhttp://www.roseindia.net/java/beginners/Threads.shtml else contact me mohammadbilal.shaikh@gmail.com

Reply | Read entire comment

using isAlive() method of thread you can find out the no of alivBy Anonymous on October 6, 2009, 12:23 pmusing isAlive() method of thread you can find out the no of alive threads in program...

Reply | Read entire comment

counting alive threadsBy Anonymous on October 1, 2009, 12:34 pmCan you suggest a way for finding out the number of alive threads in a program..

Reply | Read entire comment

Little nitpickBy Anonymous on September 27, 2009, 8:48 pmDid you guys actually capitalize an instance variable in that example? (int Count) I'm ashamed and appalled good sirs!

Reply | Read entire comment

niceBy Anonymous on September 25, 2009, 1:52 pmThat's a nice tutorial for everybody who needs to refresh their knowledge in Java. Beginners should read and understand the concepts of object oriented language......

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources