Multithreading in Java

Multithreading Usually a program has logic to execute and some objects or data to modify. In a single threaded system program executes in a sequence line by line. Multithreaded system can allow multiple threads to execute a program parallel in multiple instances. If there is any part of code dealing with the object data modification, there is no guarantee that it will not be attempted any more than one thread at a time. Now there a need to make sure that such kind of code should be executed exclusively. To achieve this in Java we a concept of LOCK. Using Lock mechanism thread holds complete hold on an object and object is also can not be access any other thread except the thread holding that lock. Lock is an object level control and one thread only can hold it at a time. Synchronized: We have to specify about the piece of code in a program which should be run exclusively. It could be a code segment or a complete function. Synchronised can be used in following ways: Function level synchronise will fetch a lock on the object, this function is defined in. 1) synchronised function updateTotal(){ .. .. } 2) a block of code can also be defined as synchronised with an specified object, to capture a lock control on. function updateTotal(){ .. .. Synchronised(this){ .. .. } } Thread Sates or Life cycle. Thread follwos a life cycle, which starts from the threation till it is destroyed. New State: This is the first state when thread object is created. Thread will be in this state untill the run method is not called of. Runnable: Once the run method is called, thread goes in the runnble state. While it is in a runnable state it is eligible to get process time to execute its part. Process though will keep disributing the time among all the active threads. Thread can also move to waiting state due to two reasons. 1 Timed waiting 2: Object waiting. Threads not in runnable states do not get process time. TimedWaiting: Tread is forced to wait for some period of time may be by using Thread.sleep method. It will automatically come back to runnable state once specifiled time is over. ObjectWaiting: Some time a thread need a lock on a object and that object is being used bus another prohram or thread, in this case thread will wait for this object untill the object is not free. Some time this can cause a deadlock schenario if there is a possiblility that threads are using same objects in multiple situations and if the program is not designed properly. Inter Thread Communication: When threads are trying to access a common object and that is bieng used by another thread. Theres has to be some way to notify the waiting threads once that object becomes free. This is achieved by wait,notify, notifyAll machanism. Wait and Notify is a machanism by which we can send signals between the thread when some specific condition is met. Live Example: package multithreading; import java.util.ArrayList; import java.util.Random; public class MultiThread_wait { PoolC pool; MultiThread_wait(){ pool = new PoolC(); pool.addItem(1); } class PoolC{ boolean isFull; PoolC(){ isFull = false; } synchronized void addItem(int temp){ System.out.println(”Came to check for adding..”); if(!isFull){ System.out.println(”adding”); isFull=true; notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } synchronized void printItem(){ System.out.println(”Came to check for printing..”); if(isFull){ System.out.println(”printing”); isFull=false; notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class supplier implements Runnable{ int i = 1; public void run() { while(true){ Random rd = new Random(); int temp = rd.nextInt(); pool.addItem(temp); try{ Thread.sleep(4000); }catch(Exception ex){ ex.printStackTrace(); } } } } class consumer implements Runnable{ int i =1; public void run() { System.out.println(”Running thread two ..”); while(true){ { pool.printItem(); try{ Thread.sleep(100); }catch(Exception ex){ ex.printStackTrace(); } } } } } public static void main(String[] args) { // TODO Auto-generated method stub MultiThread_wait mts = new MultiThread_wait(); supplier th1 = supplier(); Thread th11 = new Thread(th1); th11.start(); consumer th2 = consumer(); Thread th21 = new Thread(th2); th21.start(); } } Above Example demonstrate three classes Pool , Consumer and Supplier as all are part defined under the main program so that class Consumer and Supplier have direct access to the object of Class Pool. Otherwise if they are we can also pass PoolC class object to Consumer and Supplies class constructor if they are not under a same class. Notify() and NotifyAll(): It’s a good question to ask that what’s difference between notify() and notifyAll() methos. Notify() method will send a signal to one of the thread waiting for the same object (this may depend on any criteria like thread priprity or it can also be random). Whereas notifyAll() will send signal to all the threads who are waiting for that object and then it is upto the processor which therads it allows to execute. Sleep() method: Sleep method is a static method and called from the Thread class directly. Thread.sleep(100) and it throws intereuptException, so you have to catch it also. wait() method: Wait is the method of Object class and should always be called from the synchronised block of code.