CS8392 - OOPs - UNIT - 4 - PPT - 4.1
CS8392 - OOPs - UNIT - 4 - PPT - 4.1
OBJECT ORIENTED
PROGRAMMING
VASANTHA KUMAR V,AP/CSE
Multitasking
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.
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
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Commonly used methods of 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
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
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
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
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
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
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
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
1) public void setDaemon(boolean status) is used to mark the current thread as daemon thread or
user 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
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..
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...
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.....
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