即使我运行程序也获得不同的线程顺序 [英] Getting different thread order even time I run my program

查看:61
本文介绍了即使我运行程序也获得不同的线程顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我线程开始执行的顺序吗?我写了下面的代码

can someone tell me the order in which a thread starts to execute?. I have written the following code

class NewThread implements Runnable {
    Thread t;
    NewThread() {
        //creating a second thread.
        t=new Thread(this,"Demo Thread");
        System.out.println("Child Thread:"+t);
        t.start();
    }

    public void run() {
        try {
            for(int i=0;i<5;i++) {
                System.out.println("Child Thread:"+i);
                Thread.sleep(3000);
            }
        } catch(Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
        System.out.println("Exiting Child Thread");
    }
}

还有这个

public class ThreadDemo {
    public static void main(String args[]) {
        new NewThread();
        try {
            for(int i=0;i<5;i++) {
                System.out.println("Main Thread:"+i);
                Thread.sleep(3000);
            }
        } catch(Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
        System.out.println("Exiting Main Thread");
    }
}

执行此代码时,我得到许多不同的输出.

when I execute this code, I get many different sets of output.

Child Thread:Thread[Demo Thread,5,main]
Main Thread:0
Child Thread:0
Child Thread:1
Main Thread:1
Main Thread:2
Child Thread:2
Main Thread:3
Child Thread:3
Main Thread:4
Child Thread:4
Exiting Main Thread
Exiting Child Thread

另一个,

Child Thread:Thread[Demo Thread,5,main]
Main Thread:0
Child Thread:0
Child Thread:1
Main Thread:1
Child Thread:2
Main Thread:2
Child Thread:3
Main Thread:3
Child Thread:4
Main Thread:4
Exiting Child Thread
Exiting Main Thread

为什么会这样?线程顺序永远不会相同吗?如果有人可以给我一些有关线程和示例基础的知识,那就太好了. P.S:我是线程的新手,这是我的第一个线程程序.预先感谢.

Why is this occurring? Will the thread order never be same?? and it would be nice, if someone can give me pointers to basics of threading and examples. P.S: I am new to threads and this is my first thread program. Thanks in advance.

推荐答案

执行此代码时,我得到许多不同的输出.

when I execute this code, I get many different sets of output.

这是预期的.该顺序未定义,并且随着线程开始运行并由操作系统进行线程调度而受竞争条件的限制.

This is expected. The order is not defined and is subject to race conditions as the threads start running and are subjected to thread scheduling by the OS.

我们编写多线程应用程序的全部原因是线程是异步的,并且出于速度原因而在单独的处理器中运行.为了保证特定的输出顺序,您可以在带有锁之类的线程之间进行同步,但是这样会降低性能,并且减少了分叉线程的整个原因.

The whole reason why we write multi-threaded applications is that the threads are asynchronous and run in separate processors for speed reasons. To guarantee specific output order, you could synchronize between the threads with locks and the like but you would then lose performance and the whole reason for forking threads would be diminished.

这篇关于即使我运行程序也获得不同的线程顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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