Java Threads — a quick walkthrough

This is just a point-to-point discussion, not a very details explanation with examples. If you are looking for more details about threads, please check the below links with the given topics.

Threads in Java

States of Threads

Synchronization in Threads

Deadlock in Java

Volatile keyword

Let’s begin the quick walkthrough on Threads in Java.

Thread life cycle

  • New
  • Ready (Runnable)
  • Running
  • Wait / Blocked / Sleep
  • Dead

Thread creation

A thread can be created by following methods

  • Extending Thread class
  • Implementing the Runnable interface

Extending Thread class

  • In this way above code will be executed without any errors, even without overriding the run() method.
  • It will call run() of the Thread class.
  • But you won’t get any output.

Implementing the Runnable interface

  • When you implement the runnable interface, you have to override the run() method.

run( ) without start( )

  • You can execute the run method without the start().
  • But it will not create a new thread, instead, it will run in the main thread.
  • If you need to create a thread, you must start the thread using the start() method.

Override the start( )

  • You can override the start()
  • But it won’t create a new thread
  • If you need to override the start() method and start a new thread, you have to call super.start()

Overload the run( )

  • You can overload the run () but Start() of the Thread class will always invoke the run() with no args.

Thread priority

  • Each thread has a priority.
  • It starts from 1 to 10 and the highest priority is 10 while the lowest is 1.
  • The default priority of the main thread is 5.
  • If you set the thread priority out of 10, it will give a compile-time error

Exception in thread “main” java.lang.IllegalArgumentException

Waiting / Blocked / Sleeping state

sleep()

  • If a thread is going to sleep, that means the thread is going to sleep at a given time, then wake up and do the rest of the things.
  • sleep() will keep the lock of the object.

wait()
  • If the thread is in the wait state, it means that the thread is going to sleep for a given time until notify() or notifyAll() methods get called.
  • wait() will release the lock of the object, so other thread can get the lock of the object.

yield()

  • This can be used when a thread wants to stop and let another thread that has the same or more priority execute.
  • If there is no satisfying thread, the existing thread will process.

join()

  • This method means, stopping executing the current thread and letting other threads execute.
  • You need to handle InterruptedException with join()

Java ExecutorService

  • If an application has few threads, it can be used threads very easily using the above methods.
  • But if an application has many threads, it will be not easy to handle this.
  • Executors can be used to avoid this complexity.
  • The executor framework is a framework that can be used for creating, managing, and executing threads.
  • This provides an asynchronous feature to Java applications.

Features of Executor service



Thread creation
  • Provides thread pool and various methods to create threads.
Thread Management
  • The thread pool will manage the life cycle of threads.
Thread Execution
  • Various methods will be provided.
  • Thread schedulers can be used.

Thread pool

  • The thread pool will manage the life cycle of threads.
  • Executor implementations use thread pools
  • A thread pool is a collection of worker threads, which are ready to serve.
  • Creating new threads and managing them uses a big amount of data
  • Worker threads in the thread pool will help to reduce this overhead of creating threads.
  • Tasks are submitted to the pool via an internal queue called the blocking queue.
  • If there are more tasks than active threads, these tasks will be inserted into a blocking queue until a thread becomes available.
  • The common type of the thread pool is the fixed thread pool.

Fixed thread pool

  • This has a specific number of running threads
  • If a thread stops, this will replace with a new thread.
  • The main advantage of a fixed thread pool is it will limit the threads of an application.
  • It won’t let the application exceed the limit of threads that the application handles.

Executor interfaces in Java Concurrency API

Executor
  • Provides a single method execute() to create a thread.
  • (new Thread(r)).start() can be replaced with e.execute(r)
ExecutorService
  • Also provides execute() method, but this accepts both Runnable and Callable objects.
ScheduledExecutorService
  • This can be used to act in an asynchronous manner in Java
  • It can be used as periodically and after a specific timeout.
  • Runnable and Callable tasks can be executed

Callable interface

  • Runnable is void, it returns nothing
  • But Callable can return values and throw checked exception
  • This interface has only one method, call()
  • The returning object will be Future, this is like Promise in JavaScript.


There is a lot to learn about threads. This was just a quick walkthrough for beginners. You can find the same article on Medium Happy coding and happy learning :)

Java Threads — a quick walkthrough Java Threads — a quick walkthrough Reviewed by Ravi Yasas on 4:02 PM Rating: 5

No comments:

Powered by Blogger.