【发布时间】:2014-07-31 04:48:15
【问题描述】:
我试图测试/学习线程(Java)中的一些基本知识,并遇到了一个简单但令人困惑的输出。以下是我的课程
public class CopyMaster implements Runnable{
@Override
public void run() {
System.out.println("Run called from Copy Master for thread "+Thread.currentThread().getName());
}
}
我从中调用线程的主类
public class Main {
public static void main(String[] args) {
Thread[] threadArray = new Thread[4];
for(int i=0; i<threadArray.length; i++){
threadArray[i] = new Thread(new CopyMaster());
}
for(Thread t : threadArray){
//[Line of intrest]System.out.println("Starting Thread "+t.getName());
t.start();
}
}
}
OP(兴趣线未注释)
Starting Thread Thread-0
Starting Thread Thread-1
Run called from Copy Master for thread Thread-0
Starting Thread Thread-2
Run called from Copy Master for thread Thread-1
Starting Thread Thread-3
Run called from Copy Master for thread Thread-2
Run called from Copy Master for thread Thread-3
OP(带有兴趣线注释)
Run called from Copy Master for thread Thread-2
Run called from Copy Master for thread Thread-3
Run called from Copy Master for thread Thread-0
Run called from Copy Master for thread Thread-1
我已尝试多次运行代码并观察到打印输出的顺序在感兴趣的注释行中是随机的,而在未注释的行中是随机的(按顺序)...
为什么会这样?//已编辑,因为这混淆了我的意思
编辑:
我知道线程的行为不可预测,但我的主要问题是为什么它在一种情况下始终保持 oredr 以及为什么在另一种情况下存在随机行为?
【问题讨论】:
-
为什么你认为应该按顺序排列?
-
再运行几次。
-
@SotiriosDelimanolis - 我认为他需要在进行任何编码之前阅读并发基础知识。 VD',请阅读 - docs.oracle.com/javase/tutorial/essential/concurrency
-
主线程按顺序执行,其他线程在哪里并行运行,并行执行总是不可预测的。
-
两者都应该是随机的。但是当您取消注释 System.out 语句时,执行需要一些 CPU 时间。前一个线程很可能完成执行,而下一个线程是调度程序的唯一选择。我认为这就是为什么它看起来是按顺序排列的。如果你增加线程数你可能会看到序列的变化,或者你可以在run()方法中添加一个sleep语句来检查它。
标签: java multithreading