繁体   English   中英

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

[英]what is the sequence of threads in 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

因此,从上面的输出中,任何人都可以向我解释为什么第二个线程首先执行。

具有两个或多个正在运行的进程,这在某些时间彼此依赖于某种状态而不同步,这实际上是一种竞争条件 自从引入多核CPU以来,线程就可以并行运行,因此绝对无法预测哪个线程将“首先启动”,即哪个线程将首先使输出完成。

对于您的前两行:线程二1线程一0的顺序可以是启动线程并继续进行时的任何顺序。 但通常您会首先获得线程2 1,因为启动线程而不是移至下一行会花费一些时间。

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

现在,在执行此步骤之后,再次发生相同的事情。 线程一处于睡眠状态1000ms。 因此,每隔200毫秒,我们就会收到以下输出:线程二6(线程一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");

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM