1. Extending from Thread class
2. Implementing Runnable
- Extends a class from the Thread class
- Override the run( )
- Create an instance of the above class
- Start the Thread
/**
 *
 * @author paiman
 */
class DispThread extends Thread{
    String msg;
    public DispThread(String msg) {
        this.msg = msg;
    }
    @Override
    public void run(){
        for(int i=0; i<5;i++){
            System.out.println(msg);
        }
    }
}
/**
 *
 * @author paiman
 */
public class ThreadTest {
    public static void main (String[]args){
        DispThread dt1 = new DispThread("Thread");
        DispThread dt2 = new DispThread("Example");
        dt1.start();
        dt2.start();
    }
}
- Implement Runnable on a class
- Implement the run( ) of the Runnable interface
- Create an instance of the above class
- Create a Thread object by passing the Runnable object as parameter
- Start the Thread
/**
 *
 * @author paiman
 */
public class DispThread2 implements Runnable{
    String msg;
    public DispThread2(String msg) {
        this.msg = msg;
    }
    @Override
    public void run(){
        for(int i=0; i<5;i++){
            System.out.println(msg);
        }
    }
}
/**
 *
 * @author paiman
 */
public class ThreadTest2 {
    public static void main (String[]args){
        DispThread2 dt1 = new DispThread2("Thread");
        DispThread2 dt2 = new DispThread2("Example");
        Thread t1 = new Thread(dt1);
        Thread t2 = new Thread(dt2);
        t1.start();
        t2.start();
    }
}
 
 
0 comments:
Post a Comment