24 Sept 2012

thread priority example in java

/* thread priority example in java */ 

class TestA extends Thread {
    public void run() {
        System.out.println("TestA Thread started");
        for (int i = 1; i <= 4; i++) {
            System.out.println("\t From thread TestA :i=" + i);
        }
        System.out.println("exit from TestA");
    }
}

class TestB extends Thread {
    public void run() {
        System.out.println("TestB Thread started");
        for (int j = 1; j <= 4; j++) {
            System.out.println("\t From thread TestB :j=" + j);
        }
        System.out.println("exit from TestB");
    }
}

class TestC extends Thread {
    public void run() {
        System.out.println("testC Thread started");
        for (int k = 1; k <= 4; k++) {
            System.out.println("\t From thread TestC :K=" + k);
        }
        System.out.println("exit from TestC");
    }
}

public class TestThread {
    public static void main(String args[]) {

        TestA A = new TestA();
        TestB B = new TestB();
        TestC C = new TestC();

        C.setPriority(Thread.MAX_PRIORITY);
        B.setPriority(Thread.NORM_PRIORITY+1);
        A.setPriority(Thread.MIN_PRIORITY);

        System.out.println(" Begin thread A");
        A.start();

        System.out.println(" Begin thread B");
        B.start();

        System.out.println(" Begin thread C");
        C.start();

        System.out.println(" End of main thread");
    }
}

 
Output:
Begin thread A
Begin thread B
TestA Thread started
Begin thread C
From thread TestA :i=1
testC Thread started
From thread TestC :K=1
End of main thread
From thread TestC :K=2
From thread TestC :K=3
From thread TestC :K=4
exit from TestC
From thread TestA :i=2
From thread TestA :i=3
TestB Thread started
From thread TestB :j=1
From thread TestB :j=2
From thread TestB :j=3
From thread TestB :j=4
exit from TestB
From thread TestA :i=4
exit from TestA

0 comments:

Post a Comment