Sunday, 26 August 2012

Java Thread

Creating a Thread Example


We can create a thread in two ways:

1. Extends the Thread Class
2. Implements the Thread Interface

1. Creating the Thread extending Thread Class


class Test extends Thread{
    Test(){
    super("Thread One");
    }
}
public class ThreadTest2 {
    public static void main(String args[]){
        Test t=new Test();
      
        System.out.println(t);
    }

}
2. Creating the thread implementing the runnable Interface
When we implement the runnable interface then we must override the run() method.

class MyThread implements Runnable{
    String name;
    int number;
public MyThread(String n,int num) {
    this.name=n;
    this.number=num;
   
}

    @Override
    public void run() {
        System.out.println("Hello");
    }
   
    public String toString(){
        return "Thread Name:"+name+":"+"Number:"+number;
    }
}
public class ThreadTest {
public static void main(String args[]){
    MyThread myThread1=new MyThread("Testing Thread",1);
    myThread1.run();
    System.out.println(myThread1);
}
}

No comments:

Post a Comment