Pages

Program to implement threads

// Program to implement threads
public class MyThread extends Thread{
            MyThread(String s){
              super(s);
              start();
            }
            public void run(){
              for(int i=0;i<5;i++){
                System.out.println("Thread Name  :"
                        +Thread.currentThread().getName());
                try{
                  Thread.sleep(1000);
                }catch(Exception e){}
              }
            }
          }
             class MultiThread1{
            public static void main(String args[]){
              System.out.println("Thread Name :"
                     +Thread.currentThread().getName());  
              MyThread m1=new MyThread("My Thread 1");
              MyThread m2=new MyThread("My Thread 2");
            }
          }
In this program, two threads are created along with the "main" thread. The currentThread() method of the Thread class returns a reference to the  currently executing thread and the getName( ) method returns the name of the thread. The sleep( ) method pauses execution of the current thread for 1000 milliseconds(1 second) and switches to the another threads to execute it. At the time of execution of the program, both threads are registered with the thread scheduler and the CPU scheduler executes them one by one.
Now, lets create the same program implenting the Runnable interface:
Program:
package BASICS;
class MyThread1 implements Runnable{
            Thread t;
            MyThread1(String s)  {
              t=new Thread(this,s);
              t.start();
            }
           
            public void run()  {
              for(int i=0;i<5;i++) {
                System.out.println("ThreadName:"+Thread.currentThread().getName());
                try {
                Thread.sleep(1000);
                }catch(Exception e){}
              }
            }
          }

           class RunnableThread1{
            public static void main(String args[])  {
              System.out.println("ThreadName:"+Thread.currentThread().getName());  
              MyThread1 m1=new MyThread1("My Thread 1");
              MyThread1 m2=new MyThread1("My Thread 2");
            }
          }

Note that, this program gives the same output as the output of the previous example. It means, you can use either class Thread or interface Runnable to implement thread in your program