Skip to main content

Threads

What is a Thread?

A thread is the smallest unit of a process that can run concurrently with other threads. In Java, threads are instances of the Thread class or objects that implement the Runnable interface.

Why Use Threads?

  • Concurrency: Threads enable concurrent execution, allowing different tasks to progress simultaneously.
  • Responsiveness: Multithreading can enhance the responsiveness of applications, especially in scenarios involving user interfaces or parallel processing.

Creating Threads:

Extending the Thread Class:

The simplest way to create a thread is by extending the Thread class.

Example:

class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}

public class ThreadExample {
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start();
}
}

Output:

11 Value 1
11 Value 2
11 Value 3
11 Value 4
11 Value 5

Implementing the Runnable Interface:

Another approach is to implement the Runnable interface.

Example:

class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}

public class ThreadExample {
public static void main(String args[]) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}

Output:

12 Value 1
12 Value 2
12 Value 3
12 Value 4
12 Value 5

Anonymous Threads (Lambda Expression):

For simple tasks, you can use anonymous classes or lambdas.

Example:

public class ThreadExample {
public static void main(String args[]) {
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
});

t1.start();
}
}

Output:

13 Value 1
13 Value 2
13 Value 3
13 Value 4
13 Value 5

Thread States and Lifecycle:

Thread States:

Threads in Java can be in different states:

  • New: A thread that's been created but not yet started.
  • Runnable: A thread that's ready to run is moved to the runnable state.
  • Blocked: A thread that is blocked, waiting for a monitor lock.
  • Waiting: A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • Timed Waiting: A thread that is waiting for another thread to perform a particular action within a stipulated amount of time.
  • Terminated: A thread that has exited is in this state.

Thread Lifecycle:

The lifecycle of a thread involves the following states:

  • New: When a thread is created.
  • Runnable: When the start method is called.
  • Blocked, Waiting, Timed Waiting: In various scenarios depending on the thread's actions.
  • Terminated: When the run method completes or an unhandled exception occurs.

Thread Synchronization:Synchronized method:

To control access to resources shared by multiple threads, synchronization is essential.

Example:

class Counter {
private int count = 0;

public synchronized void increment() {
count++;
}

public synchronized int getCount() {
return count;
}
}

public class SynchronizationExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Count: " + counter.getCount());
}
}

Output:

Count: 2000

Thread Interruption:

Threads can be interrupted to stop their execution.

Example:

public class InterruptExample {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted!");
}
});

t1.start();
t1.interrupt();
}
}

In this example, the Thread.sleep method is interrupted, leading to the catch block being executed.

tip

Employ synchronization mechanisms, such as synchronized blocks and methods, when dealing with shared resources in multithreaded environments to prevent data inconsistencies.

Challenge Question

Discuss the concept of thread safety in Java. How can you ensure that your code is thread-safe, and what are the potential pitfalls to be aware of?