Anda di halaman 1dari 61

JAVA

THREADS
Thread

 Thread is A LIGHT WEIGHT PROCESS.


 Multithreading in java is a process of executing
multiple threads simultaneously.
 A thread is a lightweight sub-process
 the smallest unit of processing.
 Multiprocessing and multithreading, both are used
to achieve multitasking.
 multithreading than multiprocessing because
threads use a shared memory area.
 They don't allocate separate memory area so saves
memory
 context-switching between the threads takes less
time than process.
 Java Multithreading is mostly used in games,
animation, etc.
Advantages of Java Multithreading

 1) It doesn't block the user because threads are


independent and you can perform multiple
operations at the same time.
 2) You can perform many operations together,
so it saves time.
 3) Threads are independent, so it doesn't affect
other threads if an exception occurs in a single
thread.
Multitasking

 Multitasking is a process of executing multiple tasks


simultaneously.
We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
 1) Process-based Multitasking (Multiprocessing)

 Each process has an address in memory. In other words, each


process allocates a separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for
saving and loading registers, memory maps, updating lists, etc.
 2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.

 A thread is lightweight.

 Cost of communication between the thread is low.


Realtime Usage

PC client

Internet
Server
Local Area Network

PD
A
8
Best Example
Java Thread Methods
Stages of Thread Life
1) New
The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be
the running thread.
3) Running
The thread is in running state if the thread scheduler has
selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run()
method exits.
States of a Thread
New:
Declaration: public static final Thread.State NEW
Description: Thread state for a thread which has not yet
started.
Runnable:
Declaration: public static final Thread.State RUNNABLE
Description: Thread state for a runnable thread. A thread
in the runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the
operating system such as processor.
Blocked:

Declaration: public static final Thread.State BLOCKED


Description: Thread state for a thread blocked waiting
for a monitor lock. A thread in the blocked state is waiting
for a monitor lock to enter a synchronized block/method or
reenter a synchronized block/method after calling
Object.wait().
Waiting:
Declaration: public static final Thread.State WAITING Description: Thread
state for a waiting thread. Thread state for a waiting thread. A thread is in the
waiting state due to calling one of the following methods:
Object.wait with no timeout
Thread.join with no timeout
LockSupport.park
A thread in the waiting state is waiting for another thread to perform a
particular action.
Timed Waiting:
Declaration: public static final Thread.State TIMED_WAITING
Description: Thread state for a waiting thread with a specified waiting time.
A thread is in the timed waiting state due to calling one of the following
methods with a specified positive waiting time:
Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil
Terminated:
Declaration: public static final Thread.State TERMINATED
Description: Thread state for a terminated thread. The thread has
completed execution.
Single and Multithreaded Processes
19

threads are light-weight processes within a process

Single-threaded Process Multiplethreaded Process


Threads of
Execution

Single instruction stream Multiple instruction stream


Common
Address Space
Creation of Thread

 There are two ways of creating threads:


 1) implementing an interface

 2) extending a class

Here option 2 has its own problem of inheritance [ multiple


inheritance].
So usually interface is being preferred for the thread creation.
Extending Thread class

 Threads are implemented as objects that contains a


method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
 Create a thread:
MyThread thr1 = new MyThread();

 Start Execution of threads:


thr1.start();

21
class MultithreadingDemo extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
} }}
// Main Class
public class Multithread
{ public static void main(String[] args)
{ int n = 8; // Number of threads
for (int i=0; i<8; i++)
{ MultithreadingDemo object = new
MultithreadingDemo();
object.start();
}}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
Implementing Runnable interface

class MyThread implements Runnable


{
.....
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new Thread( myObject );
 Start Execution:
thr1.start();

24
Thread
class MultithreadingDemo implements Runnable{
public void run(){
try{
System.out.println ("Thread " + Thread.currentThread().getId() + " is
running");
}catch (Exception e){ Output:
System.out.println ("Exception is caught"); Thread8
} Thread9
}} Thread10
Thread11
class Multithread{ Thread12
public static void main(String[] args) { Thread13
int n = 8; Thread14
for (int i=0; i<8; i++){ Thread15
Thread object = new Thread(new MultithreadingDemo());
object.start();
} }}
Run VS Start

 Run() – used to run the contents for current thread.


When invoked within main function, it will consider
only single thread is running.

 Start() – used to invoke or create a new thread.


When invoked within main function, a new thread is
created whenever start is called.
Thread Priority

 In Java, each thread is assigned priority, which affects the


order in which it is scheduled for running.

 Java allows users to change priority:


 ThreadName.setPriority(intNumber)
 MIN_PRIORITY = 1

 NORM_PRIORITY=5

 MAX_PRIORITY=10

 When no priority is set, What will be priority


case?
27
Priority Setting
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getNam
e());
System.out.println("running thread priority is:"+Thread.currentThread().getPri
ority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m2.setPriority(Thread.MAX_PRIORITY);
m1.setPriority(Thread.MIN_PRIORITY); Output:
running thread name is:Thread-0
m1.start();
running thread priority is:10
m2.start(); running thread name is:Thread-1
} running thread priority is:1
}
Thread Class vs Runnable Interface

1. If we extend the Thread class, our class cannot


extend any other class
 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.
Thread Synchronization

Synchronization in Java
 Synchronization in java is the capability to control
the access of multiple threads to any shared
resource.
Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
 Thread Synchronization
 There are two types of thread synchronization
mutual exclusive and inter-thread communication.
1.Mutual Exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive

Mutual Exclusive helps keep threads from interfering


with one another while sharing data. This can be done
by three ways in java:
 by synchronized method
 by synchronized block
 by static synchronization
Java synchronized method

 Any method can be declared as synchronized by


using synchronized method.
 Synchronized method is used to lock an object for
any shared resource.
 When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.
class Table{
synchronized void printTable(int n){//synchronized method

for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e)
{System.out.println(e);}
} }}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
} }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
} }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }
 Output:
5 Output: with out
10 synchronization
Output:
15 5
20 100
10
25 200
100 15
200 300
20
300 400
400 25
500
500
Synchronized block

Synchronized block is used to lock an object for any


shared resource.
Scope of synchronized block is smaller than the
method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
Static synchronization
If you make any static method as synchronized, the
lock will be on the class not on object.

• There can be interference between t1 and t3 or t2 and t4 because t1


acquires another lock and t3 acquires another
• Static synchronization solves this problem.
class Table{

synchronized static void printTable(int n){


for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}

class MyThread2 extends Thread{


public void run(){
Table.printTable(10);
}
}

class MyThread3 extends Thread{


public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}

public class TestSynchronization4{


public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
 Output: 1 2 3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80
90 100 100 200 300 400 500 600 700 800 900
1000 1000 2000 3000 4000 5000 6000 7000 8000
9000 10000
Inter-thread communication in Java

 Inter-thread communication or Co-operation is all


about allowing synchronized threads to communicate
with each other.
 Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
 1) wait() method
 Causes current thread to release the lock and wait
until either another thread invokes the notify()
method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
 The current thread must own this object's monitor,
so it must be called from the synchronized method
only otherwise it will throw exception
Method Description

public final void wait()throws waits until object is notified.


InterruptedException

public final void wait(long waits for the specified amount of


timeout)throws InterruptedException time.
 2) notify() method
 Wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
 public final void notify()
 3) notifyAll() method
 Wakes up all threads that are waiting on this object's
monitor. Syntax:
 public final void notifyAll()
Understanding the process of inter-thread
communication
The point to point explanation of the above diagram is as
follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait()
method on the object. Otherwise it releases the lock
and exits.
4. If you call notify() or notifyAll() method, thread moves
to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock
and exits the monitor state of the object.
Java Concurrency – yield(), sleep() and join()
methods

 yield():
 Suppose there are three threads t1, t2, and t3.
 Thread t1 gets the processor and starts its execution and
thread t2 and t3 are in Ready/Runnable state.
Completion time for thread t1 is 5 hour and completion
time for t2 is 5 minutes.
 Since t1 will complete its execution after 5 hours, t2 has
to wait for 5 hours to just finish 5 minutes job.
 In such scenarios where one thread is taking too much
time to complete its execution, we need a way to prevent
execution of a thread in between if something important
is pending.
 yeild() helps us in doing so.
 import java.lang.*;

// MyThread extending Thread


class MyThread extends Thread
{
public void run()
{
for (int i=0; i<5 ; i++)
System.out.println(Thread.currentThread().getName()
+ " in control");
}
}
// Driver Class
public class yieldDemo
{
public static void main(String[]args)
{
MyThread t = new MyThread();
t.start();

for (int i=0; i<5; i++)


{
// Control passes to child thread
Thread.yield();

// After execution of child Thread


// main thread takes over
System.out.println(Thread.currentThread().getName()
+ " in control");
} }}
 Output:
 Thread-0 in control
 Thread-0 in control
 Thread-0 in control
 Thread-0 in control
 Thread-0 in control
 main in control
 main in control
 main in control
 main in control
 main in control
Deadlock in Java

 Deadlock can occur in a situation when a thread is


waiting for an object lock, that is acquired by another
thread and second thread is waiting for an object
lock that is acquired by first thread.
Starvation

 In Starvation, threads are also waiting for each other.


 But here waiting time is not infinite after some interval of
time, waiting thread always gets the resources whatever is
required to execute thread run() method.

StarvationDemo thread1 = new StarvationDemo();


thread1.setPriority(10);
StarvationDemo thread2 = new StarvationDemo();
thread2.setPriority(9);
StarvationDemo thread3 = new StarvationDemo();
thread3.setPriority(8);

thread1.start();
thread2.start();
thread3.start();
Thread Pool & Daemon Thread

 A thread pool is a collection of worker threads.


 Waiting Threads, Suspended Threads, Sleeping
Threads, all these resides in Thread Pool.

 Daemon thread in java is a service provider thread


that provides services to the user thread.
 Example: GarbageCollector
 Its life depends on user threads.
 It is a low priority background thread.
Overloading Run function
class Geeks extends Thread {
public void run() {
System.out.println(“Welcome");
}
public void run(int i)
{
System.out.println(“golden");
}}
class Test extends Geeks {
public static void main(String[] args)
{
Geeks t = new Geeks();
t.run(1); //Output: golden
t.run(); //Output: Welcome
Polling

The process of testing a condition repeatedly till it becomes true is known as


polling.

 wait()-It tells the calling thread to give up the lock and go to sleep until some
other thread enters the same monitor and calls notify().
 notify()-It wakes up one single thread that called wait()
 notifyAll()-It wakes up all the threads that called wait()

synchronized(this)
{
System.out.println("producer thread running");
wait();
System.out.println(“waiting thread");
}
MultiThread - Example

public class TestThread1 implements Runnable{


public static void main(String[] args) {
Thread TestThread1 = new Thread("Test1");
Thread TestThread2 = new Thread("Test2");
TestThread1.start();
TestThread2.start();
System.out.println("Thread names are following:");
System.out.println(TestThread1.getName());
System.out.println(TestThread2.getName());
Output:
} Test1
@Override Test2
public void run() { }
}

Anda mungkin juga menyukai