Wednesday, 30 September 2015

Java Thread :Extending Thread Class

package com.JavaInterview.Programs;

/* 
** A thread can be created in java by extending Thread class, where you must override run() method.
* Call start() method to start executing the thread object.
*/
public class ThreadExtendJIP extends Thread {
  
    public ThreadExtendJIP(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("MyThread - START "+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            //Get database connection, delete unused data from DB
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("MyThread - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }
     
}
 class ThreadRunExample {
  
    public static void main(String[] args){
        Thread t1 = new ThreadExtendJIP("t1");
        Thread t2 = new ThreadExtendJIP("t2");
        System.out.println("Starting MyThreads");
        t1.start();
        t2.start();
        System.out.println("MyThreads has been started");
         
    }
}

Output:
Starting MyThreads
MyThreads has been started
MyThread - START t1
MyThread - START t2
MyThread - END t2
MyThread - END t1


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...