ENTERPRISE APPLICATION
DEVELOPMENT-1
Tharanga Ekanayake
BSc (Special) MIS, First Class
Multithreading
• A thread is a light-weight smallest part of a process that can run concurrently with the other
parts(other threads) of the same process.
• Multithreading in Java is a process of executing multiple threads simultaneously.
• We use multithreading than multiprocessing because threads use a shared memory area.
Parameter Multiprocessing Multithreading
Multithreading helps you to
Multiprocessing helps you to create computing threads of
Basic
increase computing power. a single process to increase
computing power.
It allows you to execute Multiple threads of a single
Execution multiple processes process are executed
concurrently. concurrently.
A Multithreaded Program
Main Thread
start
start start
Thread A Thread B Thread C
Threads may switch or exchange data/results
Life Cycle of a Thread
• New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
• Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions
back to the runnable state only when another thread signals the waiting
thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when
it completes its task or otherwise terminates.
You can define and instantiate a thread in one of
two ways:
1. Extend the java.lang.Thread class.
2. Implement the Runnable interface.
Extend the java.lang.Thread class.
Implement the Runnable interface.
Another example
Another example
driverClass
class NameRunnable extends Thread
{
public void run()
{
for (int x = 1; x < 11; x++) {
System.out.println(""+Thread.currentThread().getName() +" : "+x);
}
}
}
public class one {
public static void main (String [] args) {
NameRunnable nr = new NameRunnable();
Thread one = new Thread(nr);
Thread two = new Thread(nr);
one.setName("One");
one.start();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) { }
two.setName("Two");
two.start();
}
}