我在Java線程中觀察到一種奇怪的行爲,它們看起來以順序方式運行。以下是代碼段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只有在執行完成後才能執行。爲什麼不是線程並行執行,並且當一個線程休眠時,爲什麼另一個線程沒有執行呢?我在哪裏錯了?
不要你的意思是連續的,也不序列化? – mre
你沒有啓動任何線程。 –
你從未真正創建過任何線程!相反,在一個單獨的線程中,可以串行調用每個對象的「運行」功能! –