Subclassing Thread and Overriding run

The first way to customize what a thread does when it is running is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something. Let's look at the Processus class, the first of two classes in this example, which does just that:

 

public class Processus extends Thread {
 
    static int mem;
 
    Processus(String name) {
        /* call of the super class constructor (Thread) */
        super();
                    /* setting the name */
        setName(name);
    }
   
    /* redefinition of the run() method */
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(getName()+"("+i+") = "+(mem++));
            try {
                sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {
            System.out.println("Thread "+getName()+"interrupted !");
            }
        }
        
    }
}
 

The first method in the Processus class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets the Thread's name, which is used later in the program.

The next method in the Processus class is the run method. The run method is the heart of any Thread and where the action of the Thread takes place. The run method of the Processus class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread, then sleeps for a random interval of up to 1 second.

The TestProc class provides a main method that creates three Processus threads: named "P1" , "P2" and "P3" respectively.

        class TestProc {
 
          public static void main(String args[]) {
            Processus p1 = new Processus("p1");
            Processus p2 = new Processus("p2");
            Processus p3 = new Processus("p3");
    
            p1.start();
            p2.start();
            p3.start();
 
    for (int i = 0; i < 10; i++) {
   System.out.println ("main("+i+")");
            }
          }
        }
 

The main method also starts each thread immediately following its construction by calling the start method. Compile and run the program and watch your vacation fate unfold. You should see output similar to the following:

 

main(0)
main(1)
main(2)
main(3)
main(4)
main(5)
main(6)
main(7)
main(8)
p2(0) = 0
p3(0) = 1
p1(0) = 2
main(9)
p2(1) = 3
p3(1) = 4
p1(1) = 5
p2(2) = 6
p3(2) = 7
p1(2) = 8
p2(3) = 9
p3(3) = 10
p1(3) = 11
p2(4) = 12
p3(4) = 13
p1(4) = 14
p2(5) = 15
p3(5) = 16
p1(5) = 17
p2(6) = 18
p3(6) = 19
p1(6) = 20
p2(7) = 21
p3(7) = 22
p1(7) = 23
p2(8) = 24
p3(8) = 25
p1(8) = 26
p2(9) = 27
p3(9) = 28
p1(9) = 29
 

Try This:  Change the member variable mem of Processus class as provite. Compile and run the program again. Does this change the output of the program?


 

Hosted by www.Geocities.ws

1