How to use Multiple Threads in Java with Example
GIAN Tutorials
1:06 AM
you need to first define the task which will be executed by those threads. In order to create those task, you can either use Runnable or Callable interface. If you are just learning Java chose Runnable, it's simpler one, but if you are familiar with Java multithreading and want to leverage additional features offered by Callable e.g. it can throw an exception and it can also return value, then go ahead and use Callable. Once you have task ready, you need to create an instance of Thread class. You can create as many instances as you want, but beware don't create too many Thread instances in Java because both JVM and Operating system has a limit on how many threads you can create in Java. Crossing that limit will result in java.lang.OutOfmemoryError: could not create a native thread. For the purpose of this example, creating just three threads are enough. Let's assume we create threads T1, T2, and T3. While creating we pass them an instance of your Task class, which extend