Introduction to Multithreading in Java

  • By
  • June 29, 2024
  • JAVA Programming
Introduction to Multithreading in Java

Introduction to Multithreading in Java

Multithreading in Java is a powerful feature that allows the concurrent execution of two or more parts of a program. Each part of such a program is called a thread, and each thread defines a separate path of execution. Here’s an Introduction to multithreading in Java, including how to create and manage threads.

 

Basics of Multithreading

In Java, you can create a thread in two main ways:

  • By extending the Thread class.
  • By implementing the Runnable interface.

Example 1: Extending the Thread Class

When you extend the Thread class, you need to override its run method. Here’s a simple example:

class MyThread extends Thread
public void run
for inti 0 5
try
1000 // Sleep for 1 second
catch
public class ThreadExample
public static void main
+ ” Value: ”

MyThread t1 new MyThread();
MyThread t2 new MyThread(

 

Example 2: Implementing the Runnable Interface

Implementing the ‘Runnable’ interface is generally preferred because it allows you to extend another class if necessary. Here’s how you do it:

class MyRunnable implements Runnable
public void run
for inti 0 5
]
]
try
1000 // Sleep for 1 second
catch
public class RunnableExample
public static void main
new
new
= new
new
“Value: ”

Key Methods in the Thread Class

  • start(): Starts the execution of the thread. The JVM calls the run method of this thread.
  • run(): If this thread was constructed using a separate Runnable object, then that Runnable object’s run method is called; otherwise, this method does nothing.
  • sleep(long millis): Causes the currently executing thread to sleep for the specified number of milliseconds.
  • join(): Waits for the thread to die.
  • yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute.

 

Thread Synchronization

When multiple threads access shared resources, there is a need to ensure that these resources are accessed in a thread-safe manner. This is where synchronization comes in.

Synchronized Method

 

class Table
synchronized void printTable
for inti 1 5
}
try
catch
400

}

 

class MyThread1 extends Thread
this
public void run
5
class MyThread2 extends Thread
this
public void run
100
public class TestSynchronization
public static void main
Table obj new Table // Only one object
MyThread1 t1 new MyThread1
MyThread2 t2 new MyThread2

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Classes in Pune!

 

Thread Lifecycle

A thread in Java can be in one of the following states:

  1. New: The thread is created but not yet started.
  2. Runnable: The thread is ready to run and waiting for CPU time.
  3. Blocked/Waiting: The thread is waiting for a monitor lock or another thread to perform a particular action.
  4. Timed Waiting: The thread is waiting for a specified amount of time.
  5. Terminated: The thread has completed execution.

Introduction to Multithreading in Java

 

  • New:
  • A thread is in the new state if you create an instance of the Thread class but before the invocation of start() method.
  • Example: Thread t = new Thread();

 

  • Runnable:
  • A thread transitions to the runnable state when the start() method is called. The thread is now ready to run but may not be running.
  • Example: t.start();
  • The thread scheduler can move the thread from runnable to running state.

 

  • Blocked:
  • A thread enters the blocked state when it wants to access an object’s monitor that another thread has already locked.
  • Example: If thread T1 has a synchronized block or method and thread T2 tries to enter it, T2 goes to a blocked state.

 

  • Waiting:
  • A thread enters the waiting state when it waits for another thread to perform a particular action. The thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
  • Example: wait(), join() with no timeout.

 

  • Timed Waiting:
  • A thread enters the timed waiting state when it calls methods like sleep(), wait() with a timeout, join() with a timeout, etc.
  • The thread will automatically wake up after the specified time or it can be woken up earlier by another thread.

 

  • Terminated:
  • A thread is in this state when it has finished executing. The thread will not move to any other state once it reaches this state.
  • Example: The run method has completed its execution. Explore Java Interview Questions and Answers

 

Advantages of Multithreading

  • Improved performance: By utilizing the CPU more efficiently.
  • Simplified modeling: Modeling multiple concurrent processes or asynchronous tasks is easier.
  • Better resource sharing: Threads share the same memory space, allowing for efficient communication between them.

 

Challenges of Multithreading

  • Complexity: Writing, testing, and debugging multithreaded programs is more complex than single-threaded ones.
  • Concurrency issues: Issues such as race conditions, deadlocks, and thread starvation can occur.

 

Do visit our channel to learn more: Click Here

Author:-

Chetna Malagi

Call the Trainer and Book your free demo Class For Java Call now!!!
| SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*