Multithreaded Programming


Up until now, your Java programs have only executed a single sequence of instructions. A program can run multiple sequences of instructions in parallel by using multiple threads. The JVM manages these threads and executes all of them.

The Thread class in the java.lang package allows you to create and manage threads. You define a thread by extending Thread:

 class ThreadX extends Thread {   public void run() {   ..// logic for the thread   } }

Here, ThreadX extends Thread. The run() method defines the behavior of the thread.

An instance of the thread can be created and started as shown here:

 ThreadX tx = new ThreadX(); tx.start ();

Here, the first line creates an instance of ThreadX. The second line invokes the start() method of the Thread class, which begins execution of the thread. The start() method causes the run() method of ThreadX to be executed.

The following example demonstrates how to create an application that contains a thread. The thread displays an updated counter value every second:

 class ThreadX extends Thread{   public void run() {     try {       int counter = 0;       while (true) {         Thread.sleep(1000);         System.out.println(counter++);       }     }     catch(InterruptedException ex) {       ex.printStackTrace();     }   } } class ThreadDemo {   public static void main (String args [] {     ThreadX tx = new ThreadX();     tx.start ();   } }

Output from this thread during its first three seconds is shown here:

 0 1 2

You can use threads in both applets and applications. You might, for example, create an applet that implements an animation by using a thread.

The Java language includes mechanisms to coordinate the activities of several threads in a process. Data shared by more than one thread can be corrupted unless those threads are properly synchronized. Consult the Sun documentation for more details.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net