Multithreading in Java

  • Understanding Thread Concurrency.
  • Multithreading with Thread
  • Multithreading with Runnable
  • Multithreading with ExecutorService

Understanding Thread Concurrency

Multithreading with Thread

Starting out threads..
The end.
one: 1
one: 2
two: 1
one: 3
two: 2
two: 3

Multithreading with Runnable

Starting out threads..
The end.
one: 1
two: 1
one: 2
two: 2
one: 3
two: 3
  • If you need to define your own rules for multithreading, such as a priority and so on, extending the Thread class is a good idea.
  • When using Runnable, you can let your class extend some other classes, but it will not work if extending the Thread class(java doesn’t support multiple inheritances).
  • Implementing Runnable allows the class to be used by a lot of Concurrency API classes.

Multithreading with ExecutorService

New Single Thread Executor

Start
From custom thread one: 0
From custom thread one: 1
From custom thread one: 2
End
From custom thread two: 0
From custom thread two: 1
From custom thread two: 2
  • newSingleThreadExecutor implementation can execute/submit only a single thread at a time.
  • The threads submitted by it are guaranteed to be in order. So basically when one submitted thread will finish execution, the next one will start.
  • The above example creates two custom threads, but they are not in parallel. The second submitted thread will wait for the first one and then it will start execution. You can see how End might appear in the middle of two executions, because it’s a statement from the main thread and of course it’s independent of submitted two.

New Fixed Thread Pool

Start
From custom thread one: 0
End
From custom thread two: 0
From custom thread one: 1
From custom thread two: 1
From custom thread one: 2
From custom thread two: 2
  • newFixedThreadPool creates a pool of threads based on its argument. In our example, we created a pool with 5 threads. The executor will use these 5 threads to submit threads in parallel. If the number of threads submitted exceeds pool size then the executor will wait for the next available one.
  • if we would create a pool of size 1, it would behave as newSingleThreadExecutor executor.

New Cached Thread Pool

service = Executors.newCachedThreadPool();
  • it creates a thread pool that creates new threads as needed. And it reuses the available old threads. So basically, there is no limit on the number of threads for this executor and it will reuse old threads once they are done with execution.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store