java示例中的多线程

时间:2013-07-31 13:53:27

标签: java concurrency

以下是来自tutorials point的java中的示例程序:

// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

public class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

程序的输出如下。

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

我无法理解主线程在子线程之前执行的原因。在程序中,您可以看到第一个新的NewThread()被执行。 NewThread类实例化一个新线程并在新线程上调用start()函数,然后调用run()函数。 主函数中的循环仅在创建新线程后出现。但是,当程序运行时,主线程中的循环在子线程之前运行。请帮我理解。

2 个答案:

答案 0 :(得分:3)

  

主线程中的循环在子线程之前运行。请帮我理解。

默认情况下,线程没有任何形式的同步,并且可以按任何顺序运行,其执行可能是交错的。您可以获取锁并使用它们来确保顺序,例如,如果主线程在启动子线程之前获取锁定,让子线程等待获取锁定,并让主线程在完成任务后释放锁定

答案 1 :(得分:1)

Thread.start()安排要运行的线程。之后,由JVM(和操作系统)来管理调度。线程的运行方式取决于许多因素,包括您拥有的CPU /核心数,操作系统,优先级等。

如果您需要以特定顺序运行线程,等待彼此等,那么您必须使用提供的线程工具(同步,锁等)。否则它完全是任意的。

相关问题