Network Programming
MultiThreading In
JAVA
Network Programming
May Zakarneh
Topic includes
Introduction to Thread
Creation of Thread
Life cycle of Thread
Stopping and Blocking a Thread
Thread Priority
Thread Synchronization
Using Thread Methods
Deadlock
Network Programming
May Zakarneh
Introduction to Thread
• Process and Thread are two basic units of Java
program execution.
• Process: A process is a self contained execution
environment and it can be seen as a program or
application.
• Thread: It can be called lightweight process
• Thread requires less resources to create and exists in the
process
• Thread shares the process resources
Introduction to Thread Contd.
the electricity passing •
A thread is like Threa
through the wire to the devices.
A single wire or Multi wire can power •
the devices to run.
•
• ------------
A thread is like the electricity passing through
the wire to the devices.
A single wire or Multi wire can power the devices
to run.
Multithreading
• Multithreading in java is a process of
executing multiple processes simultaneously
• A program is divided into two or more
subprograms, which can be implemented at
the same time in parallel.
• Multiprocessing and multithreading, both are
used to achieve multitasking.
• Java Multithreading is mostly used in games,
animation etc.
single-threaded vs
multithreaded programs
{ A();
newThreads {
{ A(); A1(); A2(); A3(); { A1(); A2(); A3() };
B1(); B2(); } {B1(); B2() }
}
}
Multithreading Contd.
Multithreading On a Dual Processor Desktop System
Multithreading Contd.
ADVANTAGE:
■ It doesn't block the user
■ can perform many operations together so it
saves time.
■ Threads are independent so it doesn't
affect other threads
java thread
• Each Java Run time thread is
encapsulated in a [Link]
instance.
Creation of Thread
• Threads are implemented in the form of objects.
• The run() and start() are two inbuilt methods
which helps to thread implementation
• The run() method is the heart and soul of any
thread
- It makes up the entire body of a thread
• The run() method can be initiating with the help
of start() method.
Creation of Thread Contd.
Creation of Thread Contd.
Creation of Thread Contd.
2. By implementing Runnable interface
■ Define a class that implements
Runnable interface.
■ The Runnable interface has only one
method, run(), that is to be defined in the
method with the code to be executed by
the thread.
Creation of Thread Contd.
2. By implementing Runnable interface
Commonly used Constructors of
Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
• name is a string used to identify the
thread instance
Life cycle of Thread
• During the life time of a thread, there are many
states it can enter.
• They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Life cycle of Thread Contd.
Life cycle of Thread Contd.
Newborn State:
■ The thread is born and is said to be in newborn
state.
■ The thread is not yet scheduled for running.
■ At this state, we can do only one of the following:
• Schedule it for running using start() method.
• Kill it using stop() method.
Life cycle of Thread Contd.
Runnable State:
■ The thread is ready for execution
■ Waiting for the availability of the processor.
■ The thread has joined the queue
Life cycle of Thread Contd.
Running State:
• Thread is executing
• The processor has given its time to the thread
for its execution.
• The thread runs until it gives up control on its
own or taken over by other threads.
Life cycle of Thread Contd.
Blocked State:
• A thread is said to be blocked
• It is prevented to entering into the runnable and the
running state.
• This happens when the thread is suspended, sleeping,
or waiting in order to satisfy certain requirements.
• A blocked thread is considered ''not runnable'' but not
dead and therefore fully qualified to run again.
• This state is achieved when we
Invoke suspend() or sleep() or wait() methods.
Life cycle of Thread Contd.
Dead State:
• Every thread has a life cycle.
• A running thread ends its life when it has completed
executing its run( ) method. It is a natural death.
• A thread can be killed in born, or in running, or even in
"not runnable" (blocked) condition.
• It is called premature death.
• This state is achieved when we invoke stop() method or
the thread completes it execution.
Stopping and Blocking a Thread
• Stopping a thread:
• To stop a thread from running further, we may do
so by calling its stop() method.
• This causes a thread to stop immediately and
move it to its dead state.
• It forces the thread to stop abruptly before its
completion
• It causes premature death.
• To stop a thread we use the following syntax:
[Link];)(
Stopping and Blocking a Thread
Blocking a Thread:
• A thread can also be temporarily suspended
or blocked from entering into the runnable
and subsequently running state,
1. sleep(t) // blocked for 't' milliseconds
2. suspend() // blocked until resume() method is invoked
3. wait() // blocked until notify () is invoked
Thread Priority
• Each thread is assigned a priority, which
affects the order in which it is scheduled for
•
runni ng.
• Java permits us to set the priority of a thread
using the setPriority() method as follows:
[Link](int Number);
Thread Priority contd.
• The intNumber is an integer value to which
the thread's priority is set. The Thread
class defines several priority constants:
1. public static int MIN_PRIORITY = 1
2. public static int NORM_PRIORITY =5
3. public static int MAX_PRIORITY = 10
• The default setting is NORM_PRIORITV. Most user
level processes should use NORM_PRIORITV.
Java Synchronization
• Generally threads use their own data and
methods provided inside their run{) methods.
• But if we wish to use data and methods outside
the thread's run{) method, they may compete
for the same resources and may lead to serious
problems.
• Java enables us to overcome this problem using
a technique known as Synchronization.
For ex.: One thread may try to read a record from
a file while another is still writing to the same file.
Java Synchronization contd.
• When the method declared as synchronized,
Java creates a ''monitor'' and hands it over to
the thread that calls the method first time.
synchronized\ (lock-object)
{
..........II code here is synchronized
}
Commonly used methods of
Thread class:
• public void run():
– is used to perform action for a thread.
• public void start():
– starts the execution of the [Link]
calls the run() method on the thread.
• public void sleep(long miliseconds):
– Causes the currently executing thread to
sleep (temporarily cease execution) for
the specified number of milliseconds.
Commonly used methods of
Thread class:
• public void suspend():
– is used to suspend the thread
(depricated).
• public void resume():
– is used to resume the suspended
thread(depricated).
• public void stop():
– is used to stop the thread (depricated).
Commonly used methods of
Thread class:
• public void join():
– waits for a thread to die.
• public void join(long miliseconds):
– waits for a thread to die for the specified
miliseconds.
Commonly used methods of
Thread class:
• public void interrupt():
– interrupts the thread.
• public boolean isInterrupted():
– tests if the thread has been interrupted.
• public static boolean interrupted():
– tests if the current thread has been
interrupted.
Commonly used methods of
Thread class:
• public int getId():
– returns the id of the thread.
• public [Link] getState():
– returns the state of the thread.
• public boolean isAlive():
– tests if the thread is alive.
Commonly used methods of
Thread class:
• public String toString()
– returns a text representing the
information of the Thread object that
called it.
• public void setName(String name):
– changes the name of the thread.
• public String getName():
– returns the name of the thread.
Commonly used methods of
Thread class:
• public int getPriority():
– returns the priority of the thread.
• public int setPriority(int priority):
– changes the priority of the thread.
Commonly used methods of
Thread class:
• public void setDaemon(boolean b):
– marks the thread as daemon or user
thread.
• public boolean isDaemon():
– tests if the thread is a daemon thread.
Commonly used methods of
Thread class:
• public Thread currentThread():
– returns the reference of currently executing
thread.
• public void yield():
– causes the currently executing thread object
to temporarily pause and allow other threads
to execute.
Example 1
Example 1 cont.
Example 1 cont.
• Output:
Example 2
Example 2 cont.
Example 2 cont.
• Output: