Examples

1. Extending Thread

Scenario: We are asked to create a thread that prints numbers from 1 to 5 with a 1-second pause.

package practice;

public class ThreadExamples {

    static class NumberPrinter extends Thread {

        public void run() {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Thread: " + i);
                try {
                    Thread.sleep(1000); // Sleep for 1 second
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        NumberPrinter t = new NumberPrinter();
        t.start();
    }
}

Simulate two independent threads performing tasks

Scenario: Create two threads representing background tasks that run in parallel.

Add 2 numbers in a separate thread

Scenario: We are asked to create a separate thread that performs addition of 2 numbers.

2. Implementing Runnable

Run multiple tasks using the same class

Scenario: We are asked to launch multiple threads with shared logic (e.g., printing thread names).

Access a shared variable counter safely updated by two threads

Scenario: Print a shared counter from multiple threads safely.

Add 2 numbers in a separate thread

Scenario: We are asked to create a separate thread that performs addition of 2 numbers.

3. Implementing Callable

Compute factorial of a number and return result

Scenario: We are asked to return the factorial of a number using thread.

Add 2 numbers in a separate thread

Scenario: We are asked to create a separate thread that performs addition of 2 numbers.

4. Using ExecutorService

Submit 10 print tasks with a thread pool of size 3

Scenario: We are asked to submit a batch of printing tasks to a fixed thread pool.

Schedule a periodic task every 2 seconds

Scenario: Run a health check every 2 seconds using scheduled thread pool.

Add 2 numbers in a separate thread

Scenario: We are asked to create a separate thread that performs addition of 2 numbers.

5. Using CompletableFuture

Asynchronously fetch user and print welcome message

Scenario: Simulate a service fetching a user and print a greeting message after it's done.

Chain two async operations with transformation

Scenario: Fetch user ID, then fetch user's orders based on the ID.

Combine multiple futures and wait for all

Scenario: Run two independent tasks and combine their results.

Add 2 numbers in a separate thread

Scenario: We are asked to create a separate thread that performs addition of 2 numbers.

Last updated