Multithreading Example – Part 3 – Use of Runnable

Example 1:

class First implements Runnable{
    First(){
        Thread t=new Thread(this);
        //t.setName(“abc”);
        t.start();
    }
    public void run(){
        System.out.println(“Inside Run”);
        System.out.println(“Thread Name: “+Thread.currentThread().getName());
    }
}

class E{
public static void main(String[] args){
    System.out.println(“Main Thread Name: “+Thread.currentThread().getName());
    First f=new First();
}
}

Example 2:


class M implements Runnable{
    public void run(){
        for(int i=0; i        System.out.println(Thread.currentThread().getName()+” ” +i);
           try{
                Thread.sleep(2000);
            }catch(Exception e){
                System.out.println(“EXC”);
            }
        }
    }
}

class D{
    public static void main(String[] args){
        M m=new M();
        Thread t1=new Thread(m);
        Thread t2=new Thread(m);
        Thread t3=new Thread(m);
       
        t1.setName(“First”);
        t2.setName(“Second”);
        t3.setName(“Third”);
       
        t1.start();
        t2.start();
        t3.start();
       
    }
}