Infolinks In Text Ads

Nov 2, 2010

Creating a Java Thread example

Creating A Thread -
There are two ways to create threads.

1)extends Thread Class
2)implements Runnable Interface.

Example – Through the Thread Class

public class Test extends Thread{
    private String msg;
   
    Test(String msg){
        this.msg=msg;
    }
    public void run() {
        for(int x=0; x<5; x++){
            System.out.println("-----"+msg);
        }
    }
    public static void main(String[] args){
        Thread thread1 = new Test("first Thread");
        Thread thread2 = new Test("Second Thread");
        thread1.start();
        thread2.start();
    }


Example – Through the Runnable Interface

public class Test implements Runnable{
    private String msg;
   
    Test(String msg){
        this.msg=msg;
    }
    public void run() {
        for(int x=0; x<5; x++){
            System.out.println("-----"+msg);
        }
    }
    public static void main(String[] args){
        Thread thread1 = new Thread(new Test("first Thread"));
        Thread thread2 = new Thread(new Test("Second Thread"));
        thread1.start();
        thread2.start();
    }
}

Runnable Interface is preferred because Interface support multiple inheritance.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...