繁体   English   中英

Java Threads如何工作

[英]How does Java Threads work

我是一名Java学习者,试图理解Threads。

我期待下面的程序输出,顺序

线程开始运行方法再见

但我得到了订单中的输出

再见线程启动了运行方法

这是我的代码:

public class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread("Thread started");
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Bye");
    }
}

class MyThread implements Runnable
{
    Thread t;
    String s= null;

    MyThread(String str)
    { 
      s=str;
    }

    public void run()
    {
      System.out.println(s);
      System.out.println("Run Method");
    }
}

在多线程代码中,无法保证哪个线程将以什么顺序运行。 这是多线程的核心,不仅限于Java。 你可以得到一次t1,t2,t3,t3,t1,t2等等。

在你的情况下,有2个线程。 一个是主线程,另一个是firstThread。 尚未确定哪个将首先执行。

这是线程的全部内容 - 它们同时运行(如果你的处理器只有一个核心,它是伪同步的,但程序员没有区别)。

当你在Thread对象上调用Thread.start()方法时,它是相似的(但不一样,因为它启动一个线程,而不是一个进程而且前者更耗费资源)同时启动另一个java程序。 所以firstThread.start()开始运行你的主线程的paralel(由你的main方法启动)。

这一行启动一个主执行线程(如zeroThread)

public static void main(String[] args)

您可以通过调用Thread.sleep()来引用它。

这条线

firstThread.start();

启动另一个线程,但为了引用它你使用它的名称,但是你从主线程引用它,它运行paralel到firstThread。 为了获得预期的输出,你可以加入这两个线程,就像链接它们一样:这样:

public static void main(String[] args)
{
    MyThread t1= new MyThread("Thread started");
    Thread firstThread= new Thread(t1);
    firstThread.start();
    firstThread.join();
    System.out.println("Bye");
}

join(),调用firstThread( 通过主线程 )强制主线程等待firstThread完成运行(它将暂停程序到下一个命令,即System.out.println(“Bye”);)。

main()等待一切完成时,你似乎在寻找线程(可能不止一个)。 ExecutorService提供了一种很好的方法来管理它 - 包括在时间阈值之后纾困的能力。

import java.util.concurrent.*;                                                   

class MyThread implements Runnable { // ... }                                    

class MyProgram {                                                                
  public static void main(String[] args)                                         
  {                                                                              
    MyThread t1 = new MyThread();                                            
    MyThread t2 = new MyThread();                                            
    MyThread t3 = new MyThread();                                            

    // At this point, 3 threads teed up but not running yet                  

    ExecutorService es = Executors.newCachedThreadPool();                    

    es.execute(t1);                                                          
    es.execute(t2);                                                          
    es.execute(t3);                                                          

    // All three threads now running async                                   

    // Allow all threads to run to completion ("orderly shutdown")            
    es.shutdown();                                                           

    // Wait for them all to end, up to 60 minutes.  If they do not 
    // finish before then, the function will unblock and return false:          
    boolean finshed = es.awaitTermination(60, TimeUnit.MINUTES);             

    System.out.println("Bye");                                               
  }                                                                            
}                                                                               

Java线程习惯于没有指定的顺序运行。 这适用于包括“主”线程在内的所有线程。

如果你真的想看到它的工作,试试:

class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread();
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Thread Main");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread Main i = " + i);
        }
        System.out.println("Exit from Main");
    }
}

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

不是线程启动顺序问题。 因为你真的只是开始一个线程

这实际上更像是API调用速度问题。

基本上,你有一个println()打印“bye”,一旦Thread.start()返回就会被调用。 Thread.start() 在被调用后立即返回 不等待run()调用完成。

所以你在“thread.start()”之后竞争“println”和线程初始化,并且println赢了。

作为旁注,通常,您可能希望尽可能使用ExecutorServiceCallable ,因为这些是更高级别的新API。

当您启动一个线程时,它将与当前线程并行执行,因此无法保证执行顺序。

尝试一下:

public class RunnableThread {
    static class MyThread implements Runnable {
        Thread t;
        String s= null;    
        MyThread(String str) { 
          s=str;
        }
        public void run() {
          System.out.println(s);
          System.out.println("Run Method");
        }
    }
    public static void main(String[] args) {
        MyThread t1= new MyThread("Thread started");
        Thread firstThread= new Thread(t1);
        firstThread.start();
        boolean joined = false;
        while (!joined)
            try {
                firstThread.join();
                joined = true;
            } catch (InterruptedException e) {}
        System.out.println("Bye");
    }
}

暂无
暂无

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

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