You are on page 1of 52

OS Level Multi Tasking - Process

• Typing Word Document


• Listening Music Media Player
• Downloading Video/ Materials

Programmatic Level Multi Tasking - Thread


• Running 10K Lines of Code in 10hours
• Running the same 10K lines as Two Threads each of 5k in
<10 hours
•join(): 
•It makes to wait for this thread to die. You can wait for a thread to finish by calling its join()
method.

•sleep(): It makes current executing thread to sleep for a specified interval of time. Time is in
milli seconds.

•yield(): It makes current executing thread object to pause temporarily and gives control to other
thread to execute.

•notify(): This method is inherited from Object class. This method wakes up a single thread that
is waiting on this object's monitor to acquire lock.

•notifyAll(): This method is inherited from Object class. This method wakes up all threads that
are waiting on this object's monitor to acquire lock.

•wait(): This method is inherited from Object class. This method makes current thread to wait
until another thread invokes the notify() or the notifyAll() for this object.
Synchronization

Example 1 – synchronizing methods:

public class SynchronizedCounter {


private int c = 0;
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; } public
synchronized int value() { return c; }
}

The synchronized keyword on a method means


that if this is already locked anywhere
(on this method or elsewhere) by another thread,
we need to wait till this is unlocked before Reentrant
entering the method is allowed
Synchronization

Example 2 – synchronizing blocks:


public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}

When synchronizing a block, key for the locking


should be supplied (usually would be this)
The advantage of not synchronizing the entire
method is efficiency
Synchronization

Example 3 – synchronizing using different locks:


public class TwoCounters {
private long c1 = 0, c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++; You must be
} absolutely sure
} that there is no tie
public void inc2() { between c1 and c2
synchronized(lock2) {
c2++;
}
}
}
Main Thread
Wt.withdraw(15000)
Producer consumer problem

You might also like