Today you will learn:
Thread, Runnable, Callable, and FutureExecutorServiceBy the end, you will be able to write safe concurrent programs in Java.
You can create threads using Runnable or Thread.
Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());
Thread thread = new Thread(task);
thread.start();
Thread pools help manage multiple threads efficiently.
import java.util.concurrent.*;
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());
executor.submit(task);
executor.shutdown();
Use synchronized or ReentrantLock to avoid race conditions.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
import java.util.concurrent.*;
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());
executor.submit(task);
executor.shutdown();
Create two threads that increment a shared counter safely using synchronization.
Steps:
Counter class with a synchronized increment() methodincrement() multiple timesExample:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SafeCounterExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final counter value: " + counter.getCount());
}
}