编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

内存中的线程如何执行?:How threads are executed in the memory?

MarkEWaite 线程 2022-5-13 10:31 36人围观

腾讯云服务器
内存中的线程如何执行?的处理方法

我正在学习Java中的 Thread .我试图获取正在运行的线程.但是,我无法理解输出的顺序.

I am learning about Thread in Java. I was tring to fetch which thread is running. But, I am not able to understand the order of the output.

以下是我的代码

public class practice extends Thread { public void run(){ for(int i=1;i<4;i++){ System.out.println(i); System.out.println(Thread.currentThread().getName()); } } public static void main(String[] args) { practice t1=new practice(); practice t2=new practice(); practice t3=new practice(); t1.start(); t2.start(); t3.start(); } } 

输出:

1 1 1 Thread-1 2 Thread-1 3 Thread-1 Thread-0 2 Thread-0 3 Thread-0 Thread-2 2 Thread-2 3 Thread-2 

任何人都可以帮助我了解输出顺序.预先感谢.

Can anyone help me out in understand the order of output. Thanks in advance.

问题解答

线程,就其性质而言,是彼此并发.这意味着,两个(或多个)线程在同时执行时会争用同一资源(CPU),并且CPU会按照对您的随机(不可预测)顺序将自己从一个执行切换为另一个执行.您不能也不知道您的CPU和OS体系结构将决定跳转到哪个执行路径(线程).此外,在某些语言中,这可能是 OS体系结构的问题,在某些情况下-仅是 CPU体系结构的问题,在某些情况下-都是.这取决于该语言的体系结构如何管理线程.

Threads, by their nature, are concurrent to each other. This means, that two (or more) threads compete for the same resource (CPU) when they are executed at the same time, and CPU switches itself from executing one to another in a random-to-you (unpredictable) order. You can't and won't know to which execution path (Thread) your CPU and OS architecture will decide to jump. Moreover, in some languages, this may be a question of the OS architecture, in some - the question of CPU architecture only, and in some - question of both. It depends on how that language's architecture manages threads.

请注意,即使两个线程是 parallel ,即它们在两个不同的内核上并行执行-您仍然无法预测哪个内核将首先执行指令.

Note, that even if two threads are parallel - i.e. they execute in parallel on two different cores - you still are unable to predict which core will execute instruction first.

由于以上几点,每次运行 时,您得到的代码执行顺序可能会有所不同.

Because of the points above, you may be getting a different order of execution of your code, each time you run it.

这篇关于内存中的线程如何执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^