Using Multiple Threads with Java

The Java language makes it particularly easy to do both multi-threaded programming andsocket programming. We will see in the next section that using threads is a basic technique for writing robust socket programs in Java. In this section, we will look at a shortexample program that creates a new thread class MyThread and creates 10 instances of it.

The below example contains two Java classes: MyThread and ExampleThreads. When a class, such as MyThread, is derived from the Thread class, it is expected to have a run public method. This method is called when the thread is started by calling the start method.

// File: ExampleThreads.java
//
// Example of using Java threads
//
import java.io.*;
import java.util.zip.*;

class MyThread extends Thread {
           public MyThread(String name) {
           super(name);
           this.name = name;
           } 
           public MyThread() {
           this(“no_name_thread”);
           }
           private String name;


           public void run() {
           for (int i=0; i<5; i++) {
                          System.out.println(name + “ “ + i);
                          try {
                          Thread.sleep(1000); // sleep 1 second
                          } catch (Exception e) {
                         System.out.println(“Thread sleep exception: “ + e);
                         }
           }
           }
}


public class ExampleThreads {
           static public void main(String [] args) {
           // make an array of MyThread objects:
           MyThread threads[] = new MyThread[10];
           for (int i=0; i<10; i++) {
                 threads[i] = new MyThread(“my_thread_” + i);
           }
           // now start all the threads:
           for (int i=0; i<10; i++) {
                 threads[i].start(); // calls the ‘run’ method
            }
}
}

The MyThread class was not declared public. Java requires that a file contains only one public class, and the filename must be the name of this public class with the file extension“.java”.

Here we see how threads work: you derive a class from Thread and write a run public method that performs the work in the thread. Calling the start method (inherited from the Thread class) starts the thread’s run method and immediately returns. In the first loop in ExampleThreads.main, we create 10 threads; in the second loop, we effectively start all 10 threads running simultaneously.

Posted on: 10/12/2009








0 Comments
If you want to leave a comment please Login or Register