Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Print Odd and Even number in sequence using two threads

 
One of the interview question on Thread to Print Odd and Even number in sequence using two threads. Below program will print odd and even numbers in sequential order using 2 threads. 1st thread will take care of printing odd numbers and 2nd thread will take care of printing even numbers. Here 1st thread will print odd number and go for waiting state after notifying to 2nd thread to print even number. Next 2nd thread will print even number and go for waiting state after notifying to 1st thread. Its goes on...
Print Odd and Even number in sequence using two threads



class Numbers implements Runnable{

 private int number = 1;

 @Override
 public void run() {
  
  Object lock = Thread.currentThread().getClass();
  
  if(Thread.currentThread().getName().equals("odd")){
   
   synchronized (lock) {
    while(true){
     System.out.println("ODD  : "+number++);
     lock.notify();
     try {
      Thread.sleep(100);// Just to print slowly
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
  }else{
   synchronized (lock) {
    while(true){
     try {
      Thread.sleep(100);
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("EVEN : " + number++);
     lock.notify();
    }
   } 
  }  
 }
}

public class SequenceNumber {
 
 public static void main(String[] args) throws InterruptedException {
  Numbers obj = new Numbers();

  Thread t1 = new Thread(obj, "even");
  Thread t2 = new Thread(obj, "odd");
  t1.start();
  Thread.sleep(500);
  t2.start();
 } 
}

OUTPUT:

ODD  : 1
EVEN : 2
ODD  : 3
EVEN : 4
ODD  : 5
EVEN : 6
ODD  : 7
EVEN : 8
ODD  : 9
EVEN : 10
ODD  : 11
EVEN : 12
ODD  : 13
EVEN : 14
ODD  : 15
EVEN : 16
ODD  : 17
EVEN : 18
ODD  : 19
EVEN : 20
ODD  : 21
EVEN : 22
ODD  : 23
EVEN : 24
ODD  : 25


Java Thread Local with simple example

 

Java ThreadLocal is an interesting and important Class in Java where most the developers unaware of it. Lets see what is Java ThreadLocal by its importance and how to use it with simple sample code.
Java Thread Local with simple example


What is Java ThreadLocal?
Java ThreadLocal gives the scope of an Object which stored in the ThreadLocal. We can set any Object in the Thread Local which inturns to be global access for the Thread from anywhere. 
Only thing which we need to keep in mind that to maintain a separate instance copy for each thread, so that Object conflict won't occur between multiple threads.
Values stored in ThreadLocal are local to each threads, i.e., each thread will have it's own ThreadLocal Objects where one thread can not access/modify other thread's Thread Local Objects unless it satisfies preview statement. 

Where to use Java ThreadLocal?
Lets a take situation that we need to use some global value for each thread which can be access across and anywhere the Thread is been called (For example in any methods). In those cases we can value or Object in ThreadLocal and same value or Object can be accessed anywhere in particular Thread call. 

There are 4 methods in ThreadLocal class and they are

  • initialValue() - Returns the current thread's "initial value" for this thread-local variable.
  • get() - Returns the value in the current thread's copy of this thread-local variable.
  • set() - Sets the current thread's copy of this thread-local variable to the specified value.
  • remove() - Removes the current thread's value for this thread-local variable.

Lets see simple example how to use ThreadLocal in Java.


public class MyLocalThreadHolder{
 
 private static final ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();

 public static void set(String val) {
  myThreadLocal.set(val);
 }
 
 public static void delete() {
  myThreadLocal.remove();
 }
 
 public static String get() {
 return myThreadLocal.get();
 }
}



public class TestThreadLocal extends Thread{

 public TestThreadLocal(String tName) {
  this.setName(tName);
 }
 
 public static void main(String[] args) {
 
  TestThreadLocal t1 = new TestThreadLocal("First thread...");
  TestThreadLocal t2 = new TestThreadLocal("Second thread...");
  TestThreadLocal t3 = new TestThreadLocal("Third thread...");
  
  t1.start();
  t2.start();
  t3.start();
 }
 
 @Override
 public void run() {
  //Setting thread name in ThreadLocal
  MyLocalThreadHolder.set(currentThread().getName());
  new PrintLocalThread().printThreadName(); 
 }
}



public class PrintLocalThread {
  
 public void printThreadName(){
  //Getting thread name from ThreadLocal and printing
  String currentThreadName = MyLocalThreadHolder.get();
  System.out.println("Before ----> : "+currentThreadName);
  
  //Removing value set in ThreadLocal
  MyLocalThreadHolder.delete();
  
  currentThreadName = MyLocalThreadHolder.get();
  System.out.println("After ----> : "+currentThreadName);
 }  
}


OUTPUT:


Before ----> : Second thread...
After ----> : null
Before ----> : First thread...
After ----> : null
Before ----> : Third thread...
After ----> : null



Thread join()

 
Basically Thread.join() method allows one thread to wait for the completion of another thread. Suppose if a Thread "A" is running and when we call A.join(), causes the current thread to halt its execution until A thread terminates or complete its process. By join we can make the current thread to wait for the time as same as sleep() method. Where as timing depends on the Operating System and its not on the time which we can specify. Apart from waiting time join can be interrupt by InterruptedException as same as in sleep in method. 

There are 3 types of join() methods in Java Thread class and they are 

void join()
- Waits for the current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms)
- Waits at most (ms) milliseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms, int ns)
- Waits at most (ms) milliseconds and (ms) nanoseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

Lets see simple example in Java Thread to use join() method and how its works.


public class ThreadJoinTest implements Runnable {
 
 @Override
 public void run() {
  try {
   System.out.println(Thread.currentThread().getName());
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  ThreadJoinTest obj = new ThreadJoinTest();
  for(int i=0;i<10;i++){
   Thread t = new Thread(obj);
   t.start();
   try {
    t.join();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}


OUTPUT:


Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9


If we seen above program we have used t.join() for each Thread which we have created. Since join we have used it makes other thread to wait until current thread to complete. This program will work similar to normal java code without multi-threading implementation. Please try with same code by removing t.join() where we can see normal multi-threading implementation on same Object.

OUTPUT: ( By removing t.join() )


Thread-1
Thread-3
Thread-5
Thread-7
Thread-9
Thread-0
Thread-2
Thread-4
Thread-6
Thread-8




wait(), notify(), notifyAll() in Java

 
When we come to multi-threading environment then we need of some communication between each thread like some thread has to perform task after other thread completes its task. In other way some thread has to communicate to other thread that you can takeover the Object monitor from waiting state. Basically we can say its a inter thread communication. For this we can use these methods very effectively and it does the same work for us. 

All these methods are used in Java Multi-threading and used to communicate between each threads under same Object. Just by name itself we can assume that wait() makes the thread to wait or halt for some time, notify() and notifiAll() used to indicate other threads. Lets see each one by briefly and what is the use in multi-threading. 

wait()
Makes current thread to wait and release the lock which acquired on the Object and waits for the other thread to call notify() or notifyAll() method. At the time of waiting other thread will does his process and communicate to waiting threading by calling notify or notifyAll method. One notify or notifyAll method called waiting thread will acquire the lock and it continues the process. There are 2 types of wait() methods in Java and they are 

  • wait() - Waits until other thread calls notify or notifyAll method. This method throws InterruptedException
  • wait(long milliseconds) - Waits up-to given milliseconds and it starts the process. This method also throws InterruptedException.

notify()
Once notify() called it makes waiting thread to acquire the Object and it starts the process. Suppose if more threads are waiting for the Object to acquire then any one thread will be acquire the Object monitor and the choice is arbitrary. 

notifyAll()
Once notifyAll() method called it wake-up all threads that are waiting the Objects monitor. So the difference between notify() and notifyAll() is simple that once notify() method called only one thread will wake-up and by notifyAll() method all waiting threads will go to runnable state. 

Next lets see simple example for using wait() and notify() with perfect example of amount deposit and withdraw from bank. Suppose when we withdrawing the amount if the balance is insufficient then the thread has to wait for deposit thread and then we need to withdraw the amount. For this we will be using wait() in withdraw thread and notify() in deposit thread.


public class BankTrans implements Runnable {
 
 private int amount = 0;
 
 @Override
 public synchronized void run() {
  if(Thread.currentThread().getName().equals("withdraw")){
   System.out.println("Entering to withdraw amount");
   //Trying to withdraw 5000
   if(this.amount >= 5000){
    this.amount -= 5000;
   }else{
    try {
     System.out.println("Insufficient balance and waiting for deposit....");
     wait();
     this.amount -= 5000; 
     System.out.println("Amount withdraw completed successfully :)");
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }else{
   //Depositing 10000 in user account;
   System.out.println("Entering to deposit amount");
   this.amount += 10000;
   System.out.println("Amount deposited and notifying....");
   notify();
  }
 }
 
 public static void main(String[] args) {
  BankTrans obj = new BankTrans();
  Thread withDraw = new Thread(obj, "withdraw");
  Thread deposit = new Thread(obj, "deposit");
  withDraw.start();
  deposit.start();
 }
}


OUTPUT:


Entering to withdraw amount
Insufficient balance and waiting for deposit....
Entering to deposit amount
Amount deposited and notifying....
Amount withdraw completed successfully :)





Daemon Thread in Java

 
Basically in Java there are 2 types of threads and they are Daemon Thread and non-Daemon Thread (User threads). Daemon threads are nothing but service provider for other threads to perform their task under same process like Garbage collection etc., Any Java thread can be a daemon thread and daemon threads life depends on user threads. It will be alive until all other threads are running and JVM will terminate daemon thread automatically once all other threads died. Some of the points to be remembered about daemon thread are 

  • Daemon threads are low priority threads. 
  • Daemon threads life depends on all other user threads (non-daemon threads) in same process.
  • Finally it provides only service to other user threads and nothing more than that.  
  • To specify the thread as daemon thread, just call the setDaemon method with the argument "true"  like  ( Thread.setDaemon(true) ).
  • Setting daemon should be done before starting the Thread, else it will throw IllegalThreadStateException exception. 
  • JVM will automatically exit the process once all user threads are completed and it won't wait for any Daemon thread to complete, no matter how many Daemon threads are running. 

Lets see small example with creating Daemon Thread and user threads under same process and lets see how its work.


public class DaemonThreadTest extends Thread{
 
 String daemonFlag = "";
 
 public DaemonThreadTest() { }
 
 public DaemonThreadTest(String daemonFlag) {
  this.daemonFlag = daemonFlag;
 }
 
 public void run() {
  if(daemonFlag.equals("daemon")){
   while(true){    
    try {
     System.out.println("Daemon Thread Running !!!");
     Thread.sleep(500);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }else{
   for(int i=0;i<5;i++){
    try {
     System.out.println("User Thread Running !");
     Thread.sleep(500);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }
 
 public static void main(String args[]){
    
  DaemonThreadTest daemonThread = new DaemonThreadTest("daemon");
  DaemonThreadTest userThread1 = new DaemonThreadTest();
  DaemonThreadTest userThread2 = new DaemonThreadTest();
  
  // Setting Daemon thread;
  daemonThread.setDaemon(true);
  
  daemonThread.start();
  userThread1.start();
  userThread2.start();
 }
}


OUTPUT:


Daemon Thread Running !!!
User Thread Running !
User Thread Running !
Daemon Thread Running !!!
User Thread Running !
User Thread Running !
Daemon Thread Running !!!
User Thread Running !
User Thread Running !
Daemon Thread Running !!!
User Thread Running !
User Thread Running !
Daemon Thread Running !!!
User Thread Running !
User Thread Running !
Daemon Thread Running !!!

In above sample program we can see Daemon Thread we have set in infinite loop and user threads under looping for 5 times. One all other user thread complete Daemon Thread has be terminated automatically by JVM and process get completed. No more Daemon Thread is running. 

Difference between Runnable and Callable interface in Java?

 

Runnable and Callable interface both are designed to represent task, which can be executed by any thread. Both does same task for the programmer with few difference between each other. In this tutorial we will see about difference between Runnable and Callable interface difference and when we need to use Runnable and Callable interface in our application. 

  • Runnable interface introduced in JDK 1.0, whereas Callable interface introduced in Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method.
  • Since both are interface when we implement these interface we need to implement run() method from Runnable interface and call() method from Callable interface.
  • run() method didn't not return any value, whereas call() method returns Object where Callable interface is a generic parameterized interface and Type of value is provided at implementation. 
  • Callable interface can throw checked exception because it's call method throws Exception where as run() method has its limitation. 

Basically if our application needs to return any value from executor method then we need to for Callable interface than Runnable interface.

Bu keeping all these differences and usage between Runnalbe and Callable interface programmer need to be in a position to decide which interface he needs to choose for his application. 

As this is one of the important interview question asked in most of the interviews followed by multi-threading question and mostly asked in Banking domain Java interviews. 


Future and Callable in Java

 

In our previous tutorial we have see about Java Thread Pool with Executor Framework and simple example as how its works. By using same Thread pool we will see about Callable interface working in this tutorial. 

Normally we use Runnable interface to execute multi-threading in Java. Suppose if we need to get some output or return value from run() method then we can't use Runnable interface and it won't return any value.  In case if we expect threads to return a computed result then we can use java.util.concurrent.Callable interface. The Callable object allows to return values after completion of each Thread execution. The Callable object uses generics to define the type of object which is returned and we will see simple example below as how its works along with Future.

If we submit a Callable object to an Executor the framework returns an object of type java.util.concurrent.Future. This Future object can be used to check the status of a Callable and to retrieve the result from the Callable. On the Executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method. 


import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
 
 private String name;
 
 public MyCallable(String name) {
  this.name = name;
 }
 
 @Override
 public Integer call() throws Exception {
  return name.length();
 } 
}


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallableTest {

 public static void main(String[] args) {
  
  String names[] = {"John", "David", "Steve", "Jobs", "Bill", "Gates", "Arnold"};
  
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  List<Future<Integer>> list = new ArrayList<Future<Integer>>();
     for (int i = 0; i < names.length; i++) {
       Callable<Integer> worker = new MyCallable(names[i]);
       Future<Integer> fur = executor.submit(worker);
       list.add(fur);
     }
     
     for (int i = 0; i < names.length; i++) {
      try {
       Future<Integer> future = list.get(i);
       System.out.println("NAME : ("+names[i] + ") - LENGTH : "+future.get());
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
     }  
 }
}

OUTPUT:


NAME : (John) - LENGTH : 4
NAME : (David) - LENGTH : 5
NAME : (Steve) - LENGTH : 5
NAME : (Jobs) - LENGTH : 4
NAME : (Bill) - LENGTH : 4
NAME : (Gates) - LENGTH : 5
NAME : (Arnold) - LENGTH : 6

Java Thread Pool with Executor Framework

 

Java Thread pool manages the pool of threads which are under runnable state. Thread pools contains list of all Threads in queue which are waiting to get executed. Also Thread pool can be described as collection of Runnable Objects or instance. Thread pool will be constantly running and are checking the work query for new work or Thread to be added into the pool. If there are new work or Thread to be added into the pool and executed through Thread Pool. In Java Thread class itself provides a method, e.g. execute(Runnable r) to add a new Runnable object to the work queue and execute() method will take on executing each thread in the pool.

The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination. Suppose if you want to use 1 thread pool with only 1 thread which executes several runnables you can use the Executors.newSingleThreadExecutor() method.


public class MyRunnableClass implements Runnable {

 private int value;

 MyRunnableClass(int value) {
  this.value = value;
 }

 @Override
 public void run() {
  int total = 0;
  for (int i = 1; i < value; i++) {
   total += i;
  }
  System.out.println(Thread.currentThread().getName() + " : " + total);  
 }
}


public class ThreadPoolTest {

 public static void main(String[] args) {
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  // Total 25 threads we are creating
  for (int i = 1; i <= 25; i++) {
   Runnable worker = new MyRunnableClass(i);
   executor.execute(worker);
  }
  executor.shutdown();
  System.out.println("All Threads finished...");
 }
}


OUTPUT:


pool-1-thread-1 : 0
pool-1-thread-1 : 15
pool-1-thread-1 : 21
pool-1-thread-1 : 28
pool-1-thread-1 : 36
pool-1-thread-1 : 45
pool-1-thread-1 : 55
pool-1-thread-1 : 66
pool-1-thread-1 : 78
pool-1-thread-1 : 91
pool-1-thread-1 : 105
pool-1-thread-1 : 120
pool-1-thread-1 : 136
pool-1-thread-1 : 153
pool-1-thread-1 : 171
pool-1-thread-1 : 190
pool-1-thread-1 : 210
pool-1-thread-1 : 231
pool-1-thread-1 : 253
pool-1-thread-1 : 276
pool-1-thread-1 : 300
All Threads finished...
pool-1-thread-3 : 3
pool-1-thread-4 : 6
pool-1-thread-2 : 1
pool-1-thread-5 : 10