Mutitreading in Java
Mutitreading in Java
“Thread”
• A thread is smallest unit of code that can be
dispatched by thread scheduler.
• A single program can perform multiple task
dispatching multiple threads for them.
• However only single thread will be executed at
a given point of time.
• For example Multi-Player gaming.
Multi-Tasking
• Each process requires its own separate
address space.
• Context – Switching is CPU intensive and need
lot of time.
• Inter process communication is expensive as
this mechanism span to a separate address
space.
• Processes are heavy weight.
Multi- Threading
• Multiple threads in a process share same
address space( within that process)
• Switching among multiple threads is less CPU
intensive.
• Inter thread communication is less expensive
as they share same address space.
• Threads are light weight processes.
Single Threaded Systems
• Single threaded systems use an approach Event
looping or Polling.
• In this model a single thread of control is used,
which runs in infinite loop.
• Polling is single event queue which decide which
instruction to execute next.
• Until this instruction is executed, nothing else can
happen in the system
• This results in the wastage of precious CPU cycles.
Creating Threads
There are two ways to create threads
• Extending Thread class
• Implementing Runnable Interface
Extending “Thread” class
• We can create Thread by extending Thread class.
• This class must override run() method.
• Code that should run as thread must be written
inside run() method.
• Start() method must be called to start this
thread.
• However , in turn start() will call run()
automatically.
public class ThreadByExtendingThread extends Thread{
@Override
public void run() {
super.run();
for(int i=0;i<100;i++)
{ public class ThreadsTest {
System.out.println(this.getName()+":"+i );
} public static void main(String[] args) {
} ThreadByExtendingThread tbet1=new
} Output: ThreadByExtendingThread("Mythread
Mythread1:0 1");
Mythread1:1 tbet1.start();
Mythread1:2 }
Mythread1:3
Mythread1:4 }
public static void main(String[] args) {
Thread mymainthread=Thread.currentThread();
mymainthread.setName("MAIN thread");//Main thread
ThreadByExtendingThread tbet1=new ThreadByExtendingThread("Mythread1");
ThreadByExtendingThread tbet2=new ThreadByExtendingThread("Mythread2");
tbet1.start();
tbet2.start();
}
Mythread1:0
Mythread2:0
Mythread1:1
Mythread2:1
Mythread2:2
Mythread1:2
Mythread2:3
Mythread1:3
Mythread2:4
Mythread1:4
Mythread2:5
Mythread1:5
Mythread2:6
Mythread1:6
Mythread2:7
Mythread1:7
Mythread2:8
Mythread1:8
Mythread2:9
Mythread1:9
Mythread2:10
Mythread1:10
Mythread2:11
Mythread1:11
Mythread2:12
Creating Thread by “Runnable” Interface
}
REDis running
BLUEis running
BLUEis running
REDis running
BLUEis running
REDis running
BLUEis running
REDis running
BLUEis running
REDis running
REDis running
BLUEis running
BLUEis running
Main Thread
Execution of JAVA Program starts with main
method. Main thread is created immediately as
main() method commences.
Main thread can be referred
Thread mymainthread=Thread.currentThread();
Difference between extending Thread class and
implementing Runnable interface
There is a significant difference between
Threads created by extending thread class and
implementing Runnable interface.
When we extend Thread class, we can’t extend
any other class even we require and When we
implement Runnable, we can save a space for
our class to extend any other class in future or
now
Thread Scheduler
• Thread scheduler in java is the part of the JVM that
decides which thread should run.
• There is no guarantee that which runnable thread will
be chosen to run by the thread scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time
slicing scheduling to schedule the threads.
• We can not start a Thread more than once. If
attempted so, it will throw
IllegalThreadStateException
What if we call run() method directly instead
start() method?
• Each thread starts in a separate call stack.
• Invoking the run() method from main thread,
the run() method goes onto the current call
stack rather than at the beginning of a new
call stack.
public class RunnableDemo {
public static void main(String[] args) {
Thread t1=new Thread(new
MyThread("RED"));
Thread t2=new Thread(new
MyThread("BLUE"));
t1.run();
t2.run();
System.out.println("thread finished");
}
}
REDis running
REDis running
REDis running
REDis running
REDis running
BLUEis running
BLUEis running
BLUEis running
BLUEis running
BLUEis running
thread finished
“join() method”
• The join() method waits for a thread to die. In
other words, it causes the currently running
threads to stop executing until the thread it
joins with completes its task.
• public void join()throws InterruptedException
• public void join(long milliseconds)throws
InterruptedException
public class RunnableDemo {
public static void main(String[] args) {
Thread t0=new Thread(new MyThread("BLACK"));
Thread t1=new Thread(new MyThread("RED"));
Thread t2=new Thread(new MyThread("BLUE"));
t0.start();
try {
t0.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.start();
t2.start();
System.out.println("thread finished");
}
}
BLACKis running
BLACKis running
BLACKis running
BLACKis running
BLACKis running
thread finished
BLUEis running
REDis running
REDis running
BLUEis running
REDis running
BLUEis running
REDis running
BLUEis running
BLUEis running
REDis running
Thread Priority
Each thread have a priority. Priorities are represented by
a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their
priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that
which scheduling it chooses.
3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Thank You