12/29/2008

Thread

Basic program
Extend the Thread class and override the run method


class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println("Hi");
                }
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println("World");
                }
            }
        };
        t1.start();
        t2.start();
    }
}

‘Hi’ or ‘World’ is randomly displayed.

‘Hi’ and ‘World’ are sometimes coming and going.