I'm writing a starvation simulation in Java. However, when I run it, it simply doesn't work almost any time. I'm working on MacOS. The code is like:
public class StarvationNew {
private static SharedObject sharedObject = new SharedObject(); // to jest ten obiekt (operacja) na ktorym sie blokuje
private static volatile boolean isActive = true;
public static void main(String[] args) {
Thread t1 = new Thread(new Worker(), "Thread_1");
Thread t2 = new Thread(new Worker(), "Thread_2");
Thread t3 = new Thread(new Worker(), "Thread_3");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;
}
private static class Worker implements Runnable {
private int runCount = 0;
@Override
public void run() {
while(isActive) {
sharedObject.playOperation();
runCount++;
}
System.out.println("--------");
System.out.println(Thread.currentThread().getName() + " ended with: " + runCount);
System.out.println("--------");
}
}
}
and the SharedObject just simulates long running operations looks like this:
public class SharedObject {
public synchronized void playOperation() {
try {
// long operations
System.out.println(Thread.currentThread().getName());
Thread.sleep(150);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
I wonder what is the mistake in this code.