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

查看:52
本文介绍了内存中的线程如何执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习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.

这篇关于内存中的线程如何执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆