我正在尝试创建 5 个不同的线程并尝试在run
每次将静态变量的计数增加一时在他们的方法中打印一个静态对象
这是程序的示例输出
pool-1-thread-1 Static Value before update 19
Thread going to sleep pool-1-thread-1
pool-1-thread-4 Static Value before update 19
Thread going to sleep pool-1-thread-4
pool-1-thread-3 Static Value before update 19
Thread going to sleep pool-1-thread-3
pool-1-thread-2 Static Value before update 19
Thread going to sleep pool-1-thread-2
pool-1-thread-5 Static Value before update 19
Thread going to sleep pool-1-thread-5
Thread coming out of sleep pool-1-thread-3 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-4 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-1 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-5 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-2 StaticTest.sInt 19
**pool-1-thread-5 OLD value 22 Static Value after update 23**
pool-1-thread-1 OLD value 21 Static Value after update 22
pool-1-thread-4 OLD value 20 Static Value after update 21
pool-1-thread-3 OLD value 19 Static Value after update 20
pool-1-thread-2 OLD value 23 Static Value after update 24
现在我的问题是,因为线程 3 首先从睡眠中出来,所以它必须首先打印,但是它的线程 5 首先打印,并且它的值也为 22,即静态变量在线程 5 获取它之前增加了三倍,但是为什么我在向我打印递增值时看到随机顺序,它应该以与它们从睡眠中出来的顺序相同的顺序打印,即线程 3/4/1/5/2
请倾诉思绪?我错过了什么,为什么一旦线程在睡眠后恢复运行状态,随机行为
package com.test.concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class StaticTest {
public static Integer sInt = new Integer(19);
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
es.execute(new StaticTask());
}
}
}
class StaticTask implements Runnable {
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " Static Value before update "
+ StaticTest.sInt);
try {
System.out.println("Thread going to sleep " + name);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread coming out of sleep " + name + " StaticTest.sInt " + StaticTest.sInt);
int local = StaticTest.sInt;
StaticTest.sInt = new Integer(local + 1);
System.out.println(name + " OLD value " + local +" Static Value after update "
+ StaticTest.sInt);
}
}