让我们考虑以下是我们的主题:
public class HeavyWorkRunnable implements Runnable {
@Override
public void run() {
System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
try {
doDBProcessing();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
}
private void doDBProcessing() throws InterruptedException {
// TODO
}
}
主要方法:
public class ThreadRunExample {
public static void main(String[] args){
Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
System.out.println("Starting Runnable threads");
t1.start();
t2.start();
System.out.println("Doing main heavy processing - START "+Thread.currentThread().getName());
System.out.println("Runnable Threads has been started");
}
}
现在,不同运行时间的输出是不同的。例如:
输出1:
启动可运行线程
进行主要繁重处理 - START main
进行繁重处理 - 开始 t1
进行繁重处理 - 开始 t2
进行繁重的处理 - END t2
可运行线程已启动
进行繁重处理 - END t1
输出2:
启动可运行线程
进行主要繁重处理 - START main
可运行线程已启动
进行繁重处理 - 开始 t1
进行繁重处理 - END t1
进行繁重处理 - 开始 t2
进行繁重处理 - END t2
根据我对线程的理解:
1. 一次只能运行一个线程。
2. 如果没有设置优先级,系统会随机选择线程运行。
因此,系统应该完成“主”线程的任务,然后运行 t1 或 t2。如果是这样,那么输出应始终包含:
启动可运行线程
进行主要繁重处理 - START main
可运行线程已启动
作为前三行。
我没有得到我所理解的东西。
最佳答案
问题是:操作系统及其处理队列之间有所不同。 这是一个很长的话题,但长话短说: 当三个线程在系统队列上时,操作系统让其中一个线程只运行一小部分时间(称为量子),然后将其插入队列以让其他线程运行,依此类推,以产生单处理器-单核架构中的多任务处理的错觉。为此,由于多种原因,每次执行都会有所不同。
如果您确实想深入了解这个主题,请从这里开始 link
关于java - 主线程运行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545090/