Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的多线程_Java_Multithreading - Fatal编程技术网

Java中的多线程

Java中的多线程,java,multithreading,Java,Multithreading,这是我的密码 public class ThreadLearn{ private static class Check implements Runnable{ public void run(){ System.out.printf("\nInCheck %s", Thread.currentThread().getName()); } } public static void main(String[] args){ Thread t; in

这是我的密码

public class ThreadLearn{
private static class Check implements Runnable{
    public void run(){

        System.out.printf("\nInCheck %s", Thread.currentThread().getName());
    }
}

public static void main(String[] args){

   Thread t;
   int i=0;
   while(i<2){
      t = new Thread(new GetData());
      t.start();
      System.out.printf("\n%s: ", t.getName());
      i++;
   }

}

}
我有两个问题:

  • 输出不应该是

    InRun线程-0

    线程-0:

    内螺纹-1

    线程-1:

  • 一旦
    t.start()
    完成,它会等待
    run()
    执行,然后创建第二个线程吗?如果我想做以下事情呢

    while(必需)

    新线程().start()

  • 在我的run方法中,我可以拥有我希望线程并行完成的所有内容,这样它就不会等待一个线程完成run方法,然后创建第二个线程

    谢谢

    输出不应该是

    不。线程彼此独立运行。JVM和操作系统决定何时运行哪个线程。通常,两个线程的执行顺序是不可预测的。很可能当你再次运行程序时,结果会不同

    一旦
    t.start()
    完成,它会等待
    run()
    执行,然后创建第二个线程吗


    不,不会等的。新线程的
    run();在不同的运行中,可能会有其他顺序。

    当线程启动时,它就启动了。因此,这两个System.out几乎同时执行,导致它们有时会改变顺序

    例如:

                ---- thread-0 prints out  
    Main thread |--- Prints out ----------- Prints out
                                          |Thread-1 started, prints out
    

    正如您所看到的,分支将与主代码在几乎相同的时间运行,导致它们在实际打印出来的时间之间波动

    我认为您应该修改您的代码段!这个相关的问题没什么意义,所以它已经满足了我的第2个问题,对吧?线程被创建并独立运行,无需等待任何操作。我可以把实现放在run方法中,它们将继续并行执行?@Kraken是的,这就是线程的全部意义,你可以让多个东西并行运行,相互独立。假设我创建了一个新线程
    t
    ,并且我的类
    Check
    或我希望该线程运行的任何其他类中有一个函数,那么既然
    t.method()
    不起作用,我该怎么做呢?如何做到这一点?因此,如果我想产生多个线程并让它们并行工作,我可以使用与上面相同的方法,将实现放在
    run()
    方法中,对吗?
                ---- thread-0 prints out  
    Main thread |--- Prints out ----------- Prints out
                                          |Thread-1 started, prints out