我在 Java 线程中观察到一种奇怪的行为,它们似乎以顺序方式运行。以下是代码片段
class ThreadUnsafeClass {
private static int y;
public static void incrementY() {
y++;
}
public static int getY() {
return y;
}
}
public class MultiThreadedClass implements Runnable {
int threadId;
MultiThreadedClass (int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
System.out.println("Number:"+ threadId + ";Thread Unsafe Old Value:" + ThreadUnsafeClass.getY());
try {
if (threadId == 1 || threadId ==2) {
Thread.sleep(60000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
ThreadUnsafeClass.incrementY();
System.out.println("Number:"+ threadId + ";Thread Unsafe New Value:" + ThreadUnsafeClass.getY());
}
public static void main (String []args) {
MultiThreadedClass thread1 = new MultiThreadedClass(1);
MultiThreadedClass thread2 = new MultiThreadedClass(2);
MultiThreadedClass thread3 = new MultiThreadedClass(3);
MultiThreadedClass thread4 = new MultiThreadedClass(4);
thread1.run();
thread2.run();
thread3.run();
thread4.run();
}
}
以下是相同的输出:
Number:1;Thread Unsafe Old Value:0
Number:1;Thread Unsafe New Value:1
Number:2;Thread Unsafe Old Value:1
Number:2;Thread Unsafe New Value:2
Number:3;Thread Unsafe Old Value:2
Number:3;Thread Unsafe New Value:3
Number:4;Thread Unsafe Old Value:3
Number:4;Thread Unsafe New Value:4
从上面的输出可以看出,即使线程 1 和 2 等待了一段合理的时间,即 60 秒,线程 3 和 4 仍然只有在它们完成执行时才执行。为什么线程不并行执行,当一个线程休眠时,为什么另一个线程不继续执行?我在某个地方出错了吗?