2011-08-12 35 views
1
using System; 
using System.Threading; 

// Simple threading scenario: Start a static method running 
// on a second thread. 
public class ThreadExample { 
    // The ThreadProc method is called when the thread starts. 
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends. 
    public static void ThreadProc() { 
     for (int i = 0; i < 10; i++) { 
      Console.WriteLine("ThreadProc: {0}", i); 
      // Yield the rest of the time slice. 
      Thread.Sleep(0); 
     } 
    } 

    public static void Main() { 
     Console.WriteLine("Main thread: Start a second thread."); 
     // The constructor for the Thread class requires a ThreadStart 
     // delegate that represents the method to be executed on the 
     // thread. C# simplifies the creation of this delegate. 
     Thread t = new Thread(new ThreadStart(ThreadProc)); 

     // Start ThreadProc. Note that on a uniprocessor, the new 
     // thread does not get any processor time until the main thread 
     // is preempted or yields. Uncomment the Thread.Sleep that 
     // follows t.Start() to see the difference. 
     t.Start(); 
     //Thread.Sleep(0); 

     for (int i = 0; i < 4; i++) { 
      Console.WriteLine("Main thread: Do some work."); 
      Thread.Sleep(0); 
     } 

     Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends."); 
     t.Join(); 
     Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program."); 
     Console.ReadLine(); 
    } 
} 

結果是:上的WIndows多線程

Main thread: Start a second thread. 
Main thread: Do some work. 
ThreadProc: 0 
Main thread: Do some work. 
ThreadProc: 1 
Main thread: Do some work. 
ThreadProc: 2 
Main thread: Do some work. 
ThreadProc: 3 
Main thread: Call Join(), to wait until ThreadProc ends. 
ThreadProc: 4 
ThreadProc: 5 
ThreadProc: 6 
ThreadProc: 7 
ThreadProc: 8 
ThreadProc: 9 
Main thread: ThreadProc.Join has returned. Press Enter to end program. 

我不明白,爲什麼 「ThreadProc的0」 「1」 「2」 「3主線程」 之間可以出現在「:做一些工作。」

任何人都可以幫我解釋一下嗎?謝謝!

+0

你會期望發生什麼?爲什麼? – svick

+0

請記住,即使您的系統有一個處理器,窗口仍然會安排線程工作以給出並行執行的錯覺 – iamkrillin

+0

您有一臺擁有4個cpu內核的機器。尼斯。 –

回答

1

「t.Start()」行啓動另一個線程,它在主線程正在工作時同時運行。

0

這似乎是正確的。一旦啓動ThreadProc

t.Start(); 

它與主線程同時運行。因此,系統將首先打印任何打印語句。你將得到合併的語句,因爲兩個循環同時進行。

1

我認爲這將有助於您閱讀有關計算機科學普遍的threads

線程(用我的話來說)是一個異步工作單元。您的處理器在程序中的不同線程之間跳躍,以不同的時間間隔完成工作。您獲得的好處是能夠在一個線程上執行工作,而另一個線程正在等待某些內容(如Thread.Sleep(0))。您也可以使用多核心CPU,因爲一個核心可以同時執行一個線程。

這是否解釋了一些?

0

MSDNThread.Start()方法

導致操作系統到當前 實例的狀態更改爲ThreadState.Running。 一旦線程處於ThreadState.Running狀態,操作系統可以將其調度執行。你已經清楚地提供

輸出顯示OS馬上跑線,然後切換兩個線程之間的控制,嘗試

t.Priority = ThreadPriority.Lowest; 
t.Start(); 

,看執行順序是否已經改變

1

的想法是,每個線程就像程序進程中的一個小程序。然後操作系統將CPU執行時間分爲兩部分。

睡眠呼叫加快了從一個線程切換到下一個線程。如果沒有它們,你可能看不到交織的輸出,但是你可能會再次看到這一點 - 關鍵在於,當你製作多個線程執行多個線程時,這不是你真正需要的,這就是爲什麼你必須假定任何線程都可能在任何時候執行並引導你進入鎖定和同步的概念(我相信你會在下一個或很快就會遇到)。