Java: Simple Thread Example – Creating and Starting Threads




RamThread.java

public class RamThread {
    public static void main(String args[]) {
        new ThreadTest("eBay").start();
        new ThreadTest("Paypal").start();
        new ThreadTest("Google").start();
    }
}
-------------------------------------------------------------------
ThreadTest.java
public class ThreadTest extends Thread {
    public ThreadTest(String str) {
        super(str);
    }
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Loop " + i + ": " + getName());
            try {
                sleep((int) (Math.random() * 2000));
            } catch (InterruptedException e) {
            }
        }
        System.out.println("Test Finished for: " + getName());
    }

}

Output:

Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment