`

1. Threads and Processes in Java

What is a Process?

What is a Thread?


2. Threads in Java

Creating Threads in Java

There are two primary ways to create threads in Java:

  1. Extending the Thread class:
    • Subclass the Thread class and override its run() method.

    Example:

    class MyThread extends Thread {
        public void run() {
            System.out.println("Thread is running...");
        }
    }
    
    public class ThreadExample {
        public static void main(String[] args) {
            MyThread thread = new MyThread();
            thread.start(); // Starts the thread
        }
    }
    
  2. Implementing the Runnable interface:
    • Implement the Runnable interface and pass the object to a Thread instance.

    Example:

    class MyRunnable implements Runnable {
        public void run() {
            System.out.println("Thread is running...");
        }
    }
    
    public class RunnableExample {
        public static void main(String[] args) {
            Thread thread = new Thread(new MyRunnable());
            thread.start();
        }
    }
    

Thread Lifecycle:

  1. New: Thread object is created but not yet started (new Thread()).
  2. Runnable: Thread is ready to run and waiting for CPU time.
  3. Running: Thread is executing.
  4. Blocked/Waiting: Thread is paused waiting for a resource or signal.
  5. Terminated: Thread finishes execution.

3. Key Thread Methods

Method Description
start() Starts the thread and invokes the run() method.
run() Defines the task performed by the thread.
sleep(long millis) Pauses the thread for a specified time.
join() Waits for the thread to finish execution.
isAlive() Checks if the thread is still running.
yield() Temporarily pauses the thread to allow other threads to execute.
interrupt() Interrupts a thread that is in a waiting or sleeping state.

4. AtomicInteger in Java

What is AtomicInteger?

Key Methods of AtomicInteger:

Method Description
get() Returns the current value.
set(int newValue) Sets the value to newValue.
incrementAndGet() Atomically increments the value by 1 and returns the new value.
decrementAndGet() Atomically decrements the value by 1 and returns the new value.
addAndGet(int delta) Atomically adds delta to the value and returns the new value.
compareAndSet(int expected, int update) Atomically sets the value if it matches the expected value.

Example:

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
    public static void main(String[] args) {
        AtomicInteger atomicInt = new AtomicInteger(0);

        System.out.println("Initial value: " + atomicInt.get());

        atomicInt.incrementAndGet();
        System.out.println("After increment: " + atomicInt.get());

        atomicInt.addAndGet(5);
        System.out.println("After adding 5: " + atomicInt.get());

        boolean updated = atomicInt.compareAndSet(6, 10); // If current value is 6, set to 10
        System.out.println("Compare and set successful? " + updated);
        System.out.println("Final value: " + atomicInt.get());
    }
}

Output:

Initial value: 0
After increment: 1
After adding 5: 6
Compare and set successful? true
Final value: 10

Advantages of AtomicInteger:


5. Multithreading Example Using AtomicInteger

Here’s how you can use AtomicInteger to safely update a counter in a multithreaded program:

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {
    private static final AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " - " + counter.incrementAndGet());
            }
        };

        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        thread1.start();
        thread2.start();
    }
}

Output (Order may vary):

Thread-1 - 1
Thread-1 - 2
Thread-2 - 3
Thread-1 - 4
Thread-2 - 5
Thread-2 - 6
Thread-1 - 7
Thread-1 - 8
Thread-2 - 9
Thread-2 - 10