Mark As Completed Discussion

Concurrency and Multithreading

Concurrency refers to the ability of a program to execute multiple tasks simultaneously. Multithreading is a technique used in Java to achieve concurrency by allowing multiple threads to execute concurrently within a single program.

Why Use Multithreading?

Multithreading allows you to write more efficient and responsive applications. By dividing a program into multiple threads, you can perform different tasks concurrently, improving overall performance and responsiveness.

Creating Threads in Java

In Java, you can create threads by extending the Thread class or implementing the Runnable interface.

Extending the Thread Class

TEXT/X-JAVA
1public class MyThread extends Thread {
2
3    public void run() {
4        // Code to be executed by the thread
5    }
6
7}

Implementing the Runnable Interface

TEXT/X-JAVA
1public class MyRunnable implements Runnable {
2
3    public void run() {
4        // Code to be executed by the thread
5    }
6
7}

Thread Synchronization

In a multithreaded environment, it's important to synchronize certain sections of code to prevent data races and ensure thread safety. Java provides synchronization mechanisms such as synchronized methods and blocks.

Synchronized Methods

TEXT/X-JAVA
1public class Counter {
2
3    private int count;
4
5    public synchronized void increment() {
6        count++;
7    }
8
9    public synchronized void decrement() {
10        count--;
11    }
12
13}

Synchronized Blocks

TEXT/X-JAVA
1public class Resource {
2
3    private Object lock = new Object();
4
5    public void doSomething() {
6        synchronized (lock) {
7            // Critical section
8        }
9    }
10
11}

Executors and Thread Pools

Java provides the Executor framework to manage and control the execution of threads. The ExecutorService interface represents a thread pool and provides convenient methods for submitting and managing tasks.

Example: Using a Fixed Thread Pool

TEXT/X-JAVA
1import java.util.concurrent.ExecutorService;
2import java.util.concurrent.Executors;
3
4public class Main {
5
6    public static void main(String[] args) {
7        // Create a fixed thread pool with 5 threads
8        ExecutorService executor = Executors.newFixedThreadPool(5);
9
10        // Submit tasks to the thread pool
11        for (int i = 0; i < 10; i++) {
12            executor.submit(() -> {
13                System.out.println("Thread: " + Thread.currentThread().getName() + " executing task");
14                try {
15                    Thread.sleep(1000);
16                } catch (InterruptedException e) {
17                    e.printStackTrace();
18                }
19                System.out.println("Thread: " + Thread.currentThread().getName() + " finished task");
20            });
21        }
22
23        // Shutdown the executor
24        executor.shutdown();
25    }
26
27}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment