Lecture 18 Synchronization
Lecture 18 Synchronization
Synchronization
Synchronization
What if, the threads wants to access the shared resources ?
}
What about static methods?
public class Counter{
In this example the methods are
private int count = 0;
static and hence are associated with
public static synchronized int getCount() the class object and not the instance.
{
Hence the lock is placed on the class
return count;
object that is, Counter.class object
} and not on the object itself. Any
public static other non static synchronized
synchronized methods are still available for access
setCount(int by other threads.
count)
{
this.count =
count;
}
}
Common Synchronization mistake
public class Counter{
The common mistake here is one
private int count = 0; method is static synchronized
public static synchronized int getCount() and another method is non static
synchronized.
{
return count; This makes a difference as locks
} are placed on two different
objects. The class object and the
public
instance and hence two different
synchroniz threads can access the methods
ed simultaneously.
setCount(int
count)
{
this.count =
count;
}
Synchronization Block
class Caller implements Runnable
class Callme
{
{ String msg; Callme target;
void call(String msg) Thread t;
public Caller(Callme tar,
{ S.O.P(“[“ + msg); String s)
{
try
target=tar;
{ Thread.sleep(1000); msg=s;
t=new Thread(this);
}catch(IE e) {}
t.start();
S.O.P (“]”); }
public void run()
}
{
target.call(ms
} g);
}
}
Synchronization Block
class Sync
{ P.S.V.M (-)
OUTPUT:
{ Callme target=new Callme();
Caller ob1=new Caller(target,”Hello”); [Hello[Sync[World]
]
Caller ob1=new Caller(target,”Sync”); ]
Caller ob1=new Caller(target,”World”);
try
{ ob1.t.join(); ob2.t.join();
ob3.t.join();
}catch(IE e){}
}
}
Synchronization Block
class Callme class Caller implements Runnable
{
{ String msg; Callme target;
void synchronized call(String msg) Thread t;
public Caller(Callme tar,
{ S.O.P(“[“ + msg); String s)
try {
target=tar;
{ Thread.sleep(1000); msg=s;
}catch(IE e) {} t=new Thread(this);
t.start();
S.O.P (“]”); }
} public void run()
{
target.call(ms
} g);
}
}
Synchronization Block
class Caller implements Runnable
class Callme {
String msg; Callme target;
{
Thread t;
void call(String msg) public Caller(Callme tar, String s)
{
{ S.O.P(“[“ + msg);
target=tar;
try msg=s;
t=new Thread(this);
{ Thread.sleep(1000);
t.start();
}catch(IE e) {} }
public void run()
S.O.P (“]”);
{
} synchronized(target)
{ target.call(msg); }
} }
}
Interthread Communication
The wait(), notify(), notifyAll() are used for interthread
Methods
communication. These are functions of Object class.
These method are implemented as final in Object. All three method
can be called only from within a synchronized context.