为什么我的输入显示一个线程在另一个线程之后而不是同时执行? [英] Why my input is showing one thread executing after another thread, not at the same time?

查看:94
本文介绍了为什么我的输入显示一个线程在另一个线程之后而不是同时执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了线程的概念,发现线程要同时在两个进程中运行.继承人我的代码

I researched the concept of a thread and saw that it is to have code run in two processes at the same time. Heres my code though

public class Connor extends Thread{

    public void run() {
        for(int i=0; i< 10; i ++){
            System.out.println("Hello " + i);
    }

    public static void main(String[] args){
        Connor runner1 = new Connor();
        Connor runner2 = new Connor();
        runner1.start();
        runner2.start();
    }
}

我的输出 http://imgur.com/yAZqgal

似乎两个线程确实同时启动(独立的进程,如两个前导0所示),但是一个线程执行(1-9),然后另一个线程执行(1-9).他们认为也要交织(1、2、2,...),因为这两个线程都打印到控制台.我研究发现,start是正确的方法,因为它告诉线程类在另一个线程中执行run方法?谁能解释为什么我会得到这个输出?

It seems like the two threads do start off at the same time(separate processes, as indicated by the two leading 0s) but one executes (1-9) and then the other executes (1-9). Arent they suppose to interweave as well (1,1,2,2,...) bc the threads both print to the console. I researched and saw that start is the right method to use as it tells the thread class to execute the run method in another thread? Can anyone explain why im getting this output?

推荐答案

假设您需要执行10项差事,而姐姐需要执行10项差事,而您只有一辆车.您会在每次差事之后将汽车带回去并更换驾驶员吗?当然不是.那将是荒谬的低效.每个线程基本上只需要输出流.因此,紧密地交错它们是荒谬的.

Say you have ten errands you need to do and your sister has ten errands she needs to do, and you only have one car. Do you bring the car back after each errand and switch drivers? Of course not. That would be absurdly inefficient. Each thread basically just needs the output stream. So it would be absurd to interleave them tightly.

这篇关于为什么我的输入显示一个线程在另一个线程之后而不是同时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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