我正在用Java编写饥饿模拟。但是,当我运行它时,它几乎几乎无法工作。我正在使用MacOS。代码类似于:
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("--------");
}
}
}
和SharedObject只是模拟长时间运行的操作,如下所示:
public class SharedObject {
public synchronized void playOperation() {
try {
// long operations
System.out.println(Thread.currentThread().getName());
Thread.sleep(150);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
我想知道这段代码有什么错误。
答案 0 :(得分:1)
使用Java线程时要牢记几件事。
以上所述,我的Windows 10(Java 8)计算机上的以下输出没有发现任何异常:
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_3
--------
Thread_1 ended with: 34
--------
--------
Thread_2
Thread_3 ended with: 1
--------
--------
Thread_2 ended with: 1
--------
进一步了解this。