Tuesday 3 December 2013

Thread Interaction




Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process.every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads
Inter-thread communication (Cooperation):

Cooperation(Inter-thread communication) is all about making synchronized threads 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()

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.Syntax:

public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException

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()


Wakes up all threads that are waiting on this object's monitor.
public final void notifyAll()

Example of Inter thread Communication:

class Customer{ 
int amount=1000; 
 
synchronized void withdraw(int amount){ 
System.out.println("going to withdraw..."); 
 
if(this.amount<amount){ 
System.out.println("Less balance; waiting for deposit..."); 
try{wait();}catch(Exception e){} 
} 
this.amount-=amount; 
System.out.println("withdraw completed..."); 
} 
 
synchronized void deposit(int amount){ 
System.out.println("going to deposit..."); 
this.amount+=amount; 
System.out.println("deposit completed... "); 
notify(); 
} 
} 
 
class Test{ 
public static void main(String args[]){ 
final Customer c=new Customer(); 
new Thread(){ 
public void run(){c.withdraw(1500);} 
}.start(); 
new Thread(){ 
public void run(){c.deposit(1000);} 
}.start(); 
 
}} 
Output: going to withdraw...
       Less balance; waiting for deposit...
       going to deposit...
       deposit completed...
       withdraw completed

No comments:

Post a Comment