package org.example;
public class DeadlockDemo {
private static Object resource1 = new Object();
private static Object resource2 = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread 1 acquired resource1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2) {
System.out.println("Thread 1 acquired resource2");
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (resource2) {
System.out.println("Thread 2 acquired resource2");
synchronized (resource1) {
System.out.println("Thread 2 acquired resource1");
}
}
});
thread1.start();
thread2.start();
}
}
package org.example;
public class RaceConditionDemo {
private static int counter = 0;
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 10000; i++) {
counter++;
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final counter value: " + counter);
}
}
package org.example;
import java.util.concurrent.locks.ReentrantLock;
public class StarvationDemo {
private static ReentrantLock lock = new ReentrantLock(true);
public static void main(String[] args) {
Runnable task = () -> {
System.out.println(Thread.currentThread().getName() + " is trying to acquire lock");
lock.lock();
System.out.println(Thread.currentThread().getName() + " acquired lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
};
for (int i = 1; i <= 5; i++) {
Thread thread = new Thread(task, "Thread-" + i);
thread.start();
}
}
}