为什么线程按此顺序执行?

时间:2013-08-10 14:52:54

标签: java multithreading

练习多线程java示例,这里我在A类中创建线程A,在B类中创建线程B.现在通过创建对象来启动这两个线程。我在放置代码

  package com.sri.thread;

class A extends Thread
{
    public void run()
    {
        System.out.println("Thread A");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread A i = " + i);
        }
        System.out.println("Exit from A");

    }
}
class B extends Thread
{
    public void run()
    {
        System.out.println("Thread B");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread B i = " + i);
        }
        System.out.println("Exit from B");
    }
}
public class Thread_Class
{
    public static void main(String[] args)
    {
        new A().start();    //creating A class thread object and calling run method
        new B().start();    //creating B class thread object and calling run method
        System.out.println("End of main thread");
    }
//- See more at: http://www.java2all.com/1/1/17/95/Technology/CORE-JAVA/Multithreading/Creating-Thread#sthash.mKjq1tCb.dpuf

}

我不明白执行的流程,通过调试尝试但没有得到它。执行的流程是。在这里我放置了令我困惑的输出。

    Thread A
Thread B
End of main thread
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A

为什么线程B中的循环在进入线程A的循环之前完成?

3 个答案:

答案 0 :(得分:5)

除非您有多个处理器,否则线程将以时间片为基础共享处理器。执行其中一个线程的总时间可能小于时间片,因此首先调度的线程将在另一个线程完全运行之前完成。

尝试在run方法中添加一个简短的Thread.sleep调用。

答案 1 :(得分:4)

执行多个线程时确实没有保证执行顺序。线程彼此独立。

源代码中的链接解释了它:

  

在这里你可以看到,虽然我们的程序,两个输出都不同   代码是一样的。它发生在线程程序中,因为它们正在运行   同时靠自己。线程独立运行   另一个,只要有机会就会执行。

答案 2 :(得分:1)

线程正在同时执行。一个不在另一个内部执行。每个线程获得CPU时间,做一些工作,然后等待CPU忙于其他事情。根据计算机上发生的其他情况,它每次都可能以不同的方式运行。

如果您希望线程的输出消息是隔行扫描的,那么在某种程度上,如果您将循环增加到数千次迭代,它们将是一个。现在,代码完成得非常快,很难看出它们真正并行运行。

相关问题