多线程启动方法

时间:2014-05-01 15:06:25

标签: java multithreading

Thread explained

这是一个普通的线程程序

class Counter implements Runnable {
    private int currentValue;
    public Counter() { currentValue = 0; }
    public int getValue() { return currentValue; }
    public void run() { // (1) Thread entry point
    try {
      while (currentValue < 5) {
      System.out.println(Thread.currentThread().getName() + ": " + (currentValue++)); // (2) Print thread name.
     Thread.sleep(250); // (3) Current thread sleeps.
          }
        } catch (InterruptedException e) {
           System.out.println(Thread.currentThread().getName() + " interrupted.");
           }
           System.out.println("Exit from thread: " + Thread.currentThread().getName());
         }
      }

 //_______________________________________________________________________________
public class Client {
    public static void main(String[] args) {
    Counter counterA = new Counter(); // (4) Create a counter.
    Thread worker = new Thread(counterA, "Counter A");// (5) Create a new thread.
    System.out.println(worker);
    worker.start(); // (6) Start the thread.
    try {
       int val;
       do {
         val = counterA.getValue(); // (7) Access the counter value.
         System.out.println("Counter value read by " + Thread.currentThread().getName()+ ": " + val); // (8) Print thread name.
         Thread.sleep(1000); // (9) Current thread sleeps.
           } while (val < 5);
        } catch (InterruptedException e) {
          System.out.println("The main thread is interrupted.");
       }
       System.out.println("Exit from main() method.");
     }
    }

,输出

Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.

我的问题是,即使工作线程最初在主线程进入try块之前启动,主线程执行首先开始,然后当主线程进入睡眠时,子线程开始运行。

如图所示(摘自“程序员指南Java SCJP认证:综合入门第3版”) 作者:Khalid A Mughal,Rolf W Rasmussen)描述了当在线程上调用start方法时它会立即返回。

请解释这一点,为什么在调用start方法时它立即返回并且线程在调用start方法时开始。就像调用start方法一样,它不会调用类的run方法。那么线程什么时候开始呢?

另外解释一下“对start()方法的调用是异步的。”

3 个答案:

答案 0 :(得分:1)

您无法直接强制执行/运行哪个Thread。一旦启动它,它就会在较低级别(通常是OS)处理,并且结果可能在不同的机器上甚至在不同的执行中有所不同。如果需要更多控制,则需要使用一些同步机制。

答案 1 :(得分:1)

线程未在start()的调用下同步启动。它发生在以后(异步)。换句话说,仅仅因为你调用start()并不意味着线程已经开始。

它们的原因和方式如何,可能取决于JVM和/或OS实现。

答案 2 :(得分:1)

您的整体分析中缺少三件事。

  1. 调用线程的start方法是顺序不并行。它调用并发运行Thread的方法。因此,如果在main方法中有5个语句调用start,则不会首先调用5ht。这就是JVM规范给你的'发生之前'的保证。但是,首先可以在调用第二个开始语句之前或之后调用1的run方法。这取决于更多的CPU时间切片问题而不是程序执行。
  2. 当您的程序中运行多个线程时,输出顺序是不确定的。那是因为他们并行运行。您永远不能确定相同的程序将在两台计算机上以相同的顺序运行,甚至在同一台计算机上运行两次。在您的问题中,您只发布了1个输出。一个接一个地运行程序20次并匹配输出。我相信2或3会完全不同。
  3. 最后,您的分析基于并发代码的顺序或执行。这是最大的程序员。并发程序从不打算以特定顺序或顺序运行。只是尝试让Runnable工作成为一个原子互斥的任务(与程序的其余部分或甚至其他Runnables互斥)并跟踪它自己的执行。不要将线程混合在一起。
相关问题