0% found this document useful (0 votes)
116 views76 pages

CS8392 - OOPs - UNIT - 4 - PPT - 4.1

This document discusses multitasking, multithreading, and synchronization in Java. It defines multitasking as allowing users to perform multiple tasks simultaneously using CPU switching. Multithreading creates multiple threads from a process to increase computer power. The key differences between multitasking and multithreading are discussed. The document also covers the lifecycle and states of threads in Java, how to create threads, commonly used Thread class methods, and synchronization techniques like synchronized methods and blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views76 pages

CS8392 - OOPs - UNIT - 4 - PPT - 4.1

This document discusses multitasking, multithreading, and synchronization in Java. It defines multitasking as allowing users to perform multiple tasks simultaneously using CPU switching. Multithreading creates multiple threads from a process to increase computer power. The key differences between multitasking and multithreading are discussed. The document also covers the lifecycle and states of threads in Java, how to create threads, commonly used Thread class methods, and synchronization techniques like synchronized methods and blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

CS 8392 

OBJECT ORIENTED
PROGRAMMING
VASANTHA KUMAR V,AP/CSE
Multitasking

• Multitasking is when a CPU is provided to execute multiple


tasks at a time.
•  Multitasking involves often CPU switching between the tasks,
so that users can collaborate with each program together.
Multitasking
Multithreading

• Multithreading is a system in which many threads are created


from a process through which the computer power is increased. 
• In multithreading, CPU is provided in order to execute many
threads from a process at a time, and in multithreading, process
creation is performed according to cost.
Multithreading
Difference between Multi-tasking and
Multi-threading
S.NO MULTITASKING MULTITHREADING

While in multithreading, many threads are created


In multitasking, users are allowed to perform
1. from a process through which computer power is
many tasks by CPU.
increased.

Multitasking involves often CPU switching While in multithreading also, CPU switching is often
2.
between the tasks. involved between the threads.

In multitasking, the processes share separate While in multithreading, processes are allocated
3.
memory. same memory.

Multitasking component involves While multithreading component does not involve


4.
multiprocessing. multiprocessing.
Difference between Multi-tasking and
Multi-threading
S.NO MULTITASKING MULTITHREADING

While in multithreading also, CPU is provided in


In multitasking, CPU is provided in order to
5. order to execute many threads from a process at a
execute many tasks at a time.
time.

In multitasking, processes don’t share same


While in multithreading, each process share same
6. resources, each process is allocated separate
resources.
resources.

Multitasking is slow compared to


7. While multithreading is faster.
multithreading.

In multitasking, termination of process takes While in multithreading, termination of thread takes


8.
more time. less time.
Lifecycle and States of a Thread in Java

A thread in Java at any point of time exists in any one of the following states.
A thread lies only in one of the shown states at any instant:
• New
• Runnable
• Blocked
• Waiting
• Timed Waiting
• Terminated
Lifecycle and
States of a
Thread in
Java
Life Cycle of a thread

New Thread: 
• When a new thread is created, it is in the new state. 
• The thread has not yet started to run when thread is in this state. 
• When a thread lies in the new state, it’s code is yet to be run and
hasn’t started to execute.
Life Cycle of a thread

Runnable State: 
A thread that is ready to run is moved to runnable state. 
In this state, a thread might actually be running or it might be ready
run at any instant of time. 
It is the responsibility of the thread scheduler to give the thread, time
to run.
Life Cycle of a thread

Blocked/Waiting state:
When a thread is temporarily inactive, then it’s in one of the following
states:
• Blocked
• Waiting
Life Cycle of a thread

Timed Waiting:
 A thread lies in timed waiting state when it calls a method with a time
out parameter. 
A thread lies in this state until the timeout is completed or until a
notification is received
Life Cycle of a thread

Terminated State: 
A thread terminates because of either of the following reasons:
• Because it exists normally. This happens when the code of thread has
entirely executed by the program.
• Because there occurred some unusual erroneous event, like
segmentation fault or an unhandled exception.
How to create thread

There are two ways to create a thread:


• By extending Thread class
• By implementing Runnable interface.
Thread class

Thread class provide constructors and methods to create and perform


operations on a thread.
Thread class extends Object class and implements Runnable interface.
Constructors of Thread class

• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
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 thread.JVM 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.
• public void join(): waits for a thread to die.
Commonly used methods of Thread class

• public void join(long miliseconds): waits for a thread to die for the


specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
Commonly used methods of Thread class

• public void setName(String name): changes the name of the thread.


• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
Commonly used methods of Thread class

• public boolean isAlive(): tests if the thread is alive.


• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
Commonly used methods of Thread class

• public void stop(): is used to stop the thread(depricated).


• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• 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.
Runnable interface

• The Runnable interface should be implemented by any class whose


instances are intended to be executed by a thread.
•  Runnable interface have only one method named run().
• public void run(): is used to perform action for a thread.
Starting a thread

• start() method of Thread class is used to start a newly created thread. 


It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will
run.
Java Thread Example by extending Thread class

class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  }  
Java Thread Example by implementing Runnable
interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  }  
Synchronization in Java

• Synchronization in java is the capability to control the access of


multiple threads to any shared resource.
• Java Synchronization is better option where we want to allow only
one thread to access the shared resource.
Why use Synchronization

• To prevent thread interference.


• To prevent consistency problem.
Types of Synchronization

There are two types of synchronization


• Process Synchronization
• Thread Synchronization
Thread Synchronization

There are two types of thread synchronization mutual exclusive and


inter-thread communication.
• Mutual Exclusive
• Synchronized method.
• Synchronized block.
• static synchronization.
• 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
Concept of Lock in Java

• Synchronization is built around an internal entity known as the lock or


monitor. 
• Every object has a lock associated with it. 
• By convention, a thread that needs consistent access to an object's fields has
to acquire the object's lock before accessing them, and then release the lock
when it's done with them.
• Package java.util.concurrent.locks contains several lock implementations.
Problem without Synchronization.

class Table{   class MyThread1 extends Thread{  
void printTable(int n) Table t;  
{//method not synchronized   MyThread1(Table t){  
   for(int i=1;i<=5;i++){   this.t=t;  
     System.out.println(n*i);   }  
     try{   public void run(){  
      Thread.sleep(400);   t.printTable(5);  
     }catch(Exception e) }  
{System.out.println(e);}   }
   }  
   }  }  
Problem without Synchronization ..

class MyThread2 extends Thread{   class TestSynchronization1{  
Table t;   public static void main(String args[]){  
MyThread2(Table t){   Table obj = new Table();//only one object  
this.t=t;   MyThread1 t1=new MyThread1(obj);  
}   MyThread2 t2=new MyThread2(obj);  
public void run(){   t1.start();  
t.printTable(100);   t2.start();  
}   }  
}   }
Problem without Synchronization ...

Output: 5
       100
       10
       200
       15
       300
       20
       400
       25
       500
Java synchronized method

• If you declare any method as synchronized, it is known as 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.
Problem with Synchronization.

class Table{   class MyThread1 extends Thread{  
 synchronized void printTable(int n) Table t;  
{//synchronized method   MyThread1(Table t){  
   for(int i=1;i<=5;i++){   this.t=t;  
     System.out.println(n*i);   }  
     try{   public void run(){  
      Thread.sleep(400);   t.printTable(5);  
     }catch(Exception e) }  
{System.out.println(e);}   }
   }  
   }  } 
Problem with Synchronization ..

class MyThread2 extends Thread{   class TestSynchronization1{  
Table t;   public static void main(String args[]){  
MyThread2(Table t){   Table obj = new Table();//only one object  
this.t=t;   MyThread1 t1=new MyThread1(obj);  
}   MyThread2 t2=new MyThread2(obj);  
public void run(){   t1.start();  
t.printTable(100);   t2.start();  
}   }  
}   }
Problem without Synchronization ...

Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
Synchronized Block in Java

• Synchronized block can be used to perform synchronization on any


specific resource of the method.
• Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
• If you put all the codes of the method in the synchronized block, it will
work same as the synchronized method.
Synchronized Block in Java

• 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   
}  
Problem with Synchronized Block .

class Table{   class MyThread1 extends Thread{  
   void printTable(int n){   Table t;  
   synchronized(this){//synchronized block   MyThread1(Table t){  
     for(int i=1;i<=5;i++){   this.t=t;  
      System.out.println(n*i);   }  
      try{   public void run(){  
       Thread.sleep(400);   t.printTable(5);  
      }catch(Exception e){System.out.println(e);}   }  
     }     }   }//end of the method   }
}
Problem with Synchronized Block ..

class MyThread2 extends Thread{   class TestSynchronization1{  
Table t;   public static void main(String args[]){  
MyThread2(Table t){   Table obj = new Table();//only one object  
this.t=t;   MyThread1 t1=new MyThread1(obj);  
}   MyThread2 t2=new MyThread2(obj);  
public void run(){   t1.start();  
t.printTable(100);   t2.start();  
}   }  
}   }
Problem with Synchronized Block ...

Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
Static Synchronization
If you make any static method as synchronized, the lock will be on the
class not on object.
Problem without static synchronization

• Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.
• In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.
• But there can be interference between t1 and t3 or t2 and t4 because t1 acquires
another lock and t3 acquires another lock.
• I want no interference between t1 and t3 or t2 and t4.Static synchronization
solves this problem.
Static synchronization .

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

class MyThread1 extends Thread{   class MyThread3 extends Thread{  
public void run(){   public void run(){  
Table.printTable(1);   Table.printTable(100);  
}   }  
}   }     
  
class MyThread2 extends Thread{   class MyThread4 extends Thread{  
public void run(){   public void run(){  
Table.printTable(10);   Table.printTable(1000);  
}   } }  
}  
Static synchronization ..

public class TestSynchronization4{   Output:1
public static void main(String t[]){          2
MyThread1 t1=new MyThread1();          3
MyThread2 t2=new MyThread2();          4
       5
MyThread3 t3=new MyThread3();          6
MyThread4 t4=new MyThread4();          7
t1.start();          8
t2.start();          9
t3.start();          10
t4.start();  
}  
}  
Inter-thread communication

• 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.
Inter-thread communication

It is implemented by following methods of Object class:


• wait()
• notify()
• notifyAll()
Inter-thread communication

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.
Inter-thread communication

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()
Inter-thread communication

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
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.
Inter-thread communication

Why wait(), notify() and notifyAll() methods are defined in


Object class not Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is completed.
methods
Example of inter thread communication

class Customer{   synchronized void deposit(int amount
int amount=10000;   ){  
synchronized void withdraw(int amount){   System.out.println("going to deposit..."
System.out.println("going to withdraw...");   );  
this.amount+=amount;  
if(this.amount<amount){   System.out.println("deposit completed.
System.out.println("Less balance; waiting for depo .. ");  
sit...");   notify();  
try{wait();}catch(Exception e){}   }  
}   }  
this.amount-=amount;  
System.out.println("withdraw completed...");  

Example of inter thread communication

class Test{  
public static void main(String args[]){  
final Customer c=new Customer();  
new Thread(){  
public void run(){c.withdraw(15000);}  
}.start();  
new Thread(){  
public void run(){c.deposit(10000);}  
}.start();  
  
}}  
Daemon Thread in Java

User threads are created by the application. 


Mostly Daemon threads created by the JVM. 
Mainly user threads are designed to do some specific task. Daemon
threads are design as to support the user threads.
User threads are foreground threads. 
Daemon threads are background threads. 
User threads are high priority threads.
Daemon Thread in Java

Daemon thread in java is a service provider thread that provides


services to the user thread.
There are many java daemon threads running automatically e.g. gc,
finalizer etc.
Daemon Thread in Java

Points to remember for Daemon Thread in Java


• It provides services to user threads for background supporting tasks.
It has no role in life than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.
Daemon Thread in Java

Why JVM terminates the daemon thread if there is no user thread?


  The sole purpose of the daemon thread is that it provides services to user
thread for background supporting task. If there is no user thread, why
should JVM keep running this thread. That is why JVM terminates the
daemon thread if there is no user thread.
Methods for Java Daemon thread

S.No. Method Description

1) public void setDaemon(boolean status) is used to mark the current thread as daemon thread or
user thread.

2) public boolean isDaemon() is used to check that current is daemon.


Example of Daemon thread

public class TestDaemonThread1 extends Threa public static void main(String[] args){  
d{     TestDaemonThread1 t1=new TestDaem
 public void run(){   onThread1();//creating thread  
  if(Thread.currentThread().isDaemon())   TestDaemonThread1 t2=new TestDaem
{//checking for daemon thread   onThread1();  
   System.out.println("daemon thread work");     TestDaemonThread1 t3=new TestDaem
  }   onThread1();  
  else{       t1.setDaemon(true);//now t1 is daemon
  System.out.println("user thread work");    thread  
 }        t1.start();//starting threads  
 }     t2.start();  
  t3.start();   }  }  
ThreadGroup

Java provides a convenient way to group multiple threads in a single


object.
In such way, we can suspend, resume or interrupt group of threads by
a single method call.
Java thread group is implemented by  java.lang.ThreadGroup class.
ThreadGroup

A ThreadGroup represents a set of threads.


A thread group can also include the other thread group.
The thread group creates a tree in which every thread group except the
initial thread group has a parent.
A thread is allowed to access information about its own thread group, but it
cannot access the information about its thread group's parent thread group
or any other thread groups.
Constructors of ThreadGroup class

No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given


name.

2) ThreadGroup(ThreadGroup parent, String name) creates a thread group with given


parent group and name.
Methods of ThreadGroup class.

S.N. Modifier Method Description


and Type

1) void checkAccess() This method determines if the currently running thread has
permission to modify the thread group.

2) int activeCount() This method returns an estimate of the number of active threads in
the thread group and its subgroups.

3) int activeGroupCount( This method returns an estimate of the number of active groups in
) the thread group and its subgroups.

4) void destroy() This method destroys the thread group and all of its subgroups.
Methods of ThreadGroup class..

S.N. Modifier and Method Description


Type

5) int enumerate(Thread[] list) This method copies into the specified array every active
thread in the thread group and its subgroups.

6) int getMaxPriority() This method returns the maximum priority of the thread
group.

7) String getName() This method returns the name of the thread group.

8) ThreadGroup getParent() This method returns the parent of the thread group.
Methods of ThreadGroup class...

S.N. Modifier and Method Description


Type
9) void interrupt() This method interrupts all threads in the thread
group.
10) boolean isDaemon() This method tests if the thread group is a daemon
thread group.
11) void setDaemon(boolean daemon) This method changes the daemon status of the
thread group.
12) boolean isDestroyed() This method tests if this thread group has been
destroyed.
13) void list() This method prints information about the thread
group to the standard output.
Methods of ThreadGroup class....

S.N. Modifier Method Description


and Type

14) boolean parentOf(ThreadGroup g This method tests if the thread group is either the thread
group argument or one of its ancestor thread groups.

15) void suspend() This method is used to suspend all threads in the thread
group.

16) void resume() This method is used to resume all threads in the thread
group which was suspended using suspend() method.
Methods of ThreadGroup class.....

S.N. Modifier Method Description


and Type

17) void setMaxPriority(int pri) This method sets the maximum priority of the group.

18) void stop() This method is used to stop all threads in the thread group.

19) String toString() This method returns a string representation of the Thread
group.
Example of ThreadGroup
public class ThreadGroupDemo implements  Thread t1 = new Thread(tg1, runnable,"one"
Runnable{   );  
    public void run() {             t1.start();  
          System.out.println(Thread.currentThrea           Thread t2 = new Thread(tg1, runnable
d().getName());   ,"two");  
    }             t2.start();  
   public static void main(String[] args) {             Thread t3 = new Thread(tg1, runnable
      ThreadGroupDemo runnable = new Threa ,"three");  
dGroupDemo();             t3.start();                
          ThreadGroup tg1 = new ThreadGroup("           System.out.println("Thread Group Na
Parent ThreadGroup");   me: "+tg1.getName());  
         tg1.list();       }  
   }  
THANK YOU

You might also like