java多线程中的线程序列是什么

时间:2016-02-02 10:28:30

标签: java multithreading

下面是我为了解Java多线程概念而编写的非常简单的java多线程程序。

public class test extends Thread {

    void test1(){
        System.out.println("this method is just for calling thread");
        start();
    }

    public void run(){
        try{
            for(int i =0; i<=5;i++){
                System.out.println("Thread One "+i);
                Thread.sleep(1000);
            }
        }

        catch(InterruptedException e){
            System.out.println("Thread 1 Interrupted ");
        }
        System.out.println("Exiting Thread one");
    }

    public static void main(String args[]){
        test t1= new test();
        t1.test1();

        try{
            for(int i=1; i<=10; i++){
                System.out.println("Thread Two "+i);
                Thread.sleep(200);

            }

        }
        catch(InterruptedException e){
            System.out.println("Thread Two Interrupted");
        }
        System.out.println("Exiting Thread Two");
    }
}

当我执行上述程序时,我得到以下输出:

this method is just for calling thread
Thread Two 1
Thread One 0
Thread Two 2
Thread Two 3
Thread Two 4
Thread Two 5
Thread One 1
Thread Two 6
Thread Two 7
Thread Two 8
Thread Two 9
Thread Two 10
Thread One 2
Exiting Thread Two
Thread One 3
Thread One 4
Thread One 5
Exiting Thread one

所以从上面的输出可以请任何人解释为什么第二个线程首先执行。

2 个答案:

答案 0 :(得分:0)

Having two or more processes running, which depend on each other being in a certain state at certain times without being synchronized is actually a race condition。由于线程可以 - 自引入多核CPU以来 - 实际上并行运行,因此绝对没有关于哪个线程将“首先启动”的可预测性,即哪个线程将设法首先完成其输出。

答案 1 :(得分:0)

前两行: 线程二1 线程一0 订单可以是任何东西,因为你已经开始一个线程并继续前进。但通常你会先获得Thread Two 1,因为启动Thread需要一些时间而不是移动到下一行。

现在无论何时运行第一个线程,你都会睡眠1000毫秒。睡觉主线200ms。 因此,在此之后,线程2将再次执行5(200 * 5)次,因为睡眠方法是异步调用。 因此它将打印: 线程二2 线程二3 线程二4 线程二5 线程一1

现在再次执行此步骤后,同样的事情发生了。线程1处于休眠状态1000ms。 所以在每200ms后我们收到以下输出: 线程二6(这将与Thread One 1一起看) 线程二7 线程二8 线程二9 线程二10

现在重复此循环并打印此输出。

如果您有任何疑问,请告诉我。

您可以使用join:

在线程2之前运行线程1
public static void main(String args[]){
test t1= new test();
t1.test1();
try {
    t1.join();
} catch (InterruptedException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
try{
    for(int i=1; i<=10; i++){
        System.out.println("Thread Two "+i);
        Thread.sleep(200);

    }

}
catch(InterruptedException e){
    System.out.println("Thread Two Interrupted");
}
System.out.println("Exiting Thread Two");

}