Multithreading
⢠Multithreading isa Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU.
⢠Each part of such program is called a thread.
⢠So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms:
Method 1. Extending the Thread class
Method 2. Implementing the Runnable Interface
4.
Multithreading
When a Javaprogram starts, one thread known as main thread is created, which executed code
written inside the main method, if you create a thread, then those threads are created and
started by the main thread, once started they start executing code written in their run() method.
Three different kinds of issues:
⢠Issues, which always comes
⢠Issues, which comes only sometimes, but
consistent with the same input
⢠Issues, which is truly random
5.
Thread class Runnable
SampleClass Sample Class
Method 1. Thread class Method 2. Runnable Interface
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesnāt support multiple
inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in Runnable interface.
6.
threadStates.java
Life cycle ofa Thread (Thread States)
⢠According to sun, there is only 4 states in thread life cycle in java
⢠New,
⢠Runnable,
⢠Not-runnable and
⢠Terminated.
⢠There is no running state.
7.
Life cycle ofa Thread (Thread States): The Thread Class and Methods
Thread created start()
New Ready
yield(), or
time out
run()
interrupt()
join()
Running
sleep()
run() returns
Terminated
Target
finished
Interrupted()
th
Wait for target
to finish
Blocked
Wait for time
out
Time out
Wait to be
notified
notify() or
notifyAll()
wait()
Example: thread1.java
//Program Usingextends to write a single-thread program.
import java.lang.*;
class ThreadExample extends Thread {
public ThreadExample (String name) {
extends
super (name);
}
public void run () {
System.out.println (Thread.currentThread ());
For (int i=0; i<=5; i++)
System.out.println (i);
}
}
public class thread1 {
public static void main (String args [ ]) {
ThreadExample obj = new ThreadExample ("First");
obj.start ( );
System.out.println (''This is:" + Thread.currentThread ());
OUTPUT:
}
}
ThreadExample
Thread
This is: Thread [main, 5, main]
Thread [First, 5, main]
11.
Example: thread2.java
//Program illustratesthe creation of threads using Runnable interface.
class ThreadExample implements Runnable {
Thread t;
implements
public ThreadExample (String ThreadName) {
t = new Thread (this, ThreadName);
}
public void run () {
System.out.println (Thread.currentThread () );
for (int i =0; i <=5; i++)
System.out.println (i);
}
}
OUTPUT:
public class thread2 {
public static void main (String args [ ]) {
ThreadExample obj = new ThreadExample(āFirstā);
obj.t.start ( );
System.out.println ("This is:" + Thread.currentThread ());
}
}
This is: Thread [main, 5, main]
Thread [First, 5, main]
Runnable
ThreadExample
12.
The Thread Classand Methods:
The Following methods are invoked on a particular Thread object.
Some methods are not available
java.lang.Thread DESCRIPTION
+Thread()
+Thread(task: Runnable)
+start(): void
+isAlive(): boolean
+setPriority(p: int): void
+join(): void
+sleep(millis: long): void
+yield(): void
+interrupt(): void
Creates a default thread.
Creates a thread for a specified task.
Starts the thread that causes the run() method to be invoked by the JVM.
Tests whether the thread is currently running.
Sets priority p (ranging from 1 to 10) for this thread.
Waits for this thread to finish.
Puts the runnable object to sleep for a specified time in milliseconds.
Causes this thread to temporarily pause and allow other threads to execute.
Interrupts this thread.
«interface»
java.lang.Runnable
13.
The Thread Classand Methods:
The Following methods are invoked on a particular Thread object.
Sr. No. Method & Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable
object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive
14.
The Thread Classand Methods:
The following methods in the Thread class are static. Invoking one of the static methods
performs the operation on the currently running thread.
Sr. No. Method & Description
1 public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting
to be scheduled.
2 public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number ofmilliseconds.
3 public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5 public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded
application.
15.
⢠It testsif this thread is alive.Athread is alive if it has been started and has not yet died.
⢠method used to find out the state of a thread.
⢠returns true: thread is in the Ready, Blocked, or Running state
⢠returns false: thread is new and has not started or if it is finished.
Syntax:
final boolean isAlive( )
Thread Methods: The isAlive() Method:
Thread Methods: The interrupt () Method
⢠If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException.
⢠If the thread is not in the sleeping or waiting state, calling the interrupt() method
performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to
true.
threadInterrupt.java
threadisAlive.java
16.
1. Threadwithoutjoin.java
2. Threadjoin.java
ā¢join() method is used for waiting the thread in execution until the thread on which join is
called is not completed. Remember, the thread which will wait is the thread in execution
and it will wait until the thread on which join method called is not completed.
⢠Youcan use the join() method to force one thread to wait for another thread to finish.
Syntax:
final void join( ) throws InterruptedException
Thread Methods: The join() Method
17.
Syntax:
public final voidstop()
⢠The suspend() method of thread class puts the thread from running to waiting state. This method isused if
you want to stop the thread execution and start it again when a certain event occurs.
Syntax:
public final void suspend()
⢠The resume() method of thread class is only used with suspend() method. This method is used to resume a
thread which was suspended using suspend() method. This method allows the suspended thread to start
again.
Thread Methods: deprecated: stop(), suspend(), and resume() Methods
⢠Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java.
This method stops the execution of a running thread and removes it from the waiting threads pool and
garbage collected. A thread will also move to the dead state automatically when it reaches the end of its
method. The stop() method is deprecated in Java due to thread-safetyissues.
public final void resume()
Syntax:
18.
Thread Priority:
⢠Eachthread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5).
⢠Youcan reset the priority using setPriority(int priority).
⢠Some static integral constants for priorities included in Thread Class:
⢠By default, a thread has the priority level of the thread that created it.
threadPriority.java
19.
ThreadSynchronization
⢠In Java,the threads are executed independently to each other. These types of threads are called
as asynchronous threads. But there are two problems may be occur with asynchronous threads.
⢠Two or more threads share the same resource (variable or method) while only one of them can access the
resource at one time.
⢠Race Condition
⢠Resource Conflict
threadnonsync.java
20.
Producer Consumer Problem
ThreadSynchronization
If the producer and the consumer are sharing the same kind of data in a program then
either producer may produce the data faster or consumer may retrieve an order of data and
process it without its existing.
21.
synchronized returntype MethodName(param_List)
{
// statements in the method Body
}
General form of synchronized Method is:
synchronized (object reference expression)
{
// statements to be synchronized
}
General form of synchronized block is:
ThreadSynchronization
There are two ways to synchronized the execution of code:
1.Synchronized Methods
2.Synchronized Blocks (Statements)
threadsyncB.java
threadsyncM.java
Java provide benefitsof avoiding thread pooling using inter-thread communication. The wait(), notify(),
and notifyAll() methods of Object class are used for this purpose. These method are implemented
as final methods in Object, so that all classes have them. All the three method can be called only from within
a synchronized context.
⢠wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor
and call notify.
⢠notify() wakes up a thread that called wait() on same object.
⢠notifyAll() wakes up all the thread that called wait() on same object.
These methods are declared within Object, as shown here:
⢠final void wait( ) throws InterruptedException
⢠final void notify( )
⢠final void notifyAll( )
Inter-thread communication
Producer Consumer Problem
threadInterCom.java
25.
Executor Framework
ļ¼ Withthe traditional approach of thread creation, When we create a new thread for executing a new task cause
overhead of thread creation, In order to manage this thread life-cycle, the execution time increase respectively.
ļ¼ Java has flexible thread pool implementation, called the Executor framework.
ļ¼A framework having a bunch of components that are used for managing worker threads efficiently is
referred to as Executor Framework.
ļ¼The Executor API reduces the execution of the task from the actual task to be executed through
the Executors.
ļ¼The executor framework is an implementation of the Producer-Consumer pattern.
The java.util.concurrent.Executors class provides a set of methods for creating ThreadPools of worker
threads.
ļ¼ Required for efficient Java multithreading.
25
26.
Executor Framework
public interfaceExecutor {
void execute(Runnable command) ;
}
ļ¼ Based on producer/consumer pattern
ļ¼ Producers submit tasks and consumers consume tasks
ļ¼ Decouples task submission from task execution
26
27.
Executor Framework
Based onproducer/consumer pattern
ļ¼Decouples task submission from task execution
The value of decoupling task submission from execution allows us to easily
change the execution policy
An execution policy specifies :
ļ§ In what thread a task will execute
ļ§ In what order tasks will be executed
ļ§ How many tasks may execute concurrently
ļ§ How many tasks may be pending
ļ§ Which tasks to reject if the system is overloaded
27