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