Threads in Java

785 views
optmiize_your_resume_1

What is Thread?

A thread is a lightweight subprocess, the smallest unit of processing or we can say that a thread is a series of executed statements .The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Why thread is used in Java?

We use Threads to make Java application faster by doing multiple things at the same time. In technical terms, Thread helps you to achieve parallelism in Java programs

Java Thread Benefits

  1. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
  2. Threads share their parent process data and code
  3. Context switching between threads is usually less expensive than between processes.
  4. Thread intercommunication is relatively easy than process communication.

Creating a Thread

There are two ways to create a thread.

  1. By extending Thread class
  2. By implementing Runnable interface.

It can be created by extending the Thread class and overriding its run() method:

public class Main extends Thread { public void run() { System.out.println("This code is running in a thread"); } }
Code language: Java (java)

Another way to create a thread is to implement the Runnable interface:

public class Main implements Runnable { public void run() { System.out.println("This code is running in a thread"); } }
Code language: Java (java)

20%off for Ink 280 281

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More