2010-08-13 21 views
7

線程如何與其他線程進行通信?他們不使用彼此的價值觀,那麼他們之間的溝通方式是什麼?線程如何與對方通信?

+0

除了已經給出的答案,在這裏獲得一個免費的電子書裏暗裏進行了深入的介紹瞭如何穿線工作在C# :[關於C#線程的免費電子書](http://www.albahari.com/threading/) – duesouth 2010-08-13 16:53:41

回答

1

線程可以共享值,他們只需要小心這樣做。在.Net中,最常用的方法是lock語句和Interlocked類。

4

「他們不使用彼此的價值」 - 好在同一過程中的兩個線程可以看到共同變量,所以這就是簡單的方法。因此,我們使用各種同步,鎖定,多重和sempahores等待條件並喚醒等待線程。

在Java中,您使用各種原語,如同步。您可以閱讀這個tutorial

+0

+1我不明白爲什麼不考慮這個事實。 – Luca 2010-08-13 17:03:02

5

線程可以通過幾種方式相互通信。這份清單並非詳盡無遺,但確實包含了最常用的策略。

  • 共享存儲器,如一個可變或一些其他數據結構
  • 同步原語,例如鎖和sempahores
  • 活動,像ManualResetEventAutoResetEvent

共享存儲器

public static void Main() 
{ 
    string text = "Hello World"; 
    var thread = new Thread(
    () => 
    { 
     Console.WriteLine(text); // variable read by worker thread 
    }); 
    thread.Start(); 
    Console.WriteLine(text); // variable read by main thread 
} 

同步原語

public static void Main() 
{ 
    var lockObj = new Object(); 
    int x = 0; 
    var thread = new Thread(
    () => 
    { 
     while (true) 
     { 
     lock (lockObj) // blocks until main thread releases the lock 
     { 
      x++; 
     } 
     } 
    }); 
    thread.Start(); 
    while (true) 
    { 
    lock (lockObj) // blocks until worker thread releases the lock 
    { 
     x++; 
     Console.WriteLine(x); 
    } 
    } 
} 

活動

public static void Main() 
{ 
    var are = new AutoResetEvent(false); 
    var thread = new Thread(
    () => 
    { 
     while (true) 
     { 
     Thread.Sleep(1000); 
     are.Set(); // worker thread signals the event 
     } 
    }); 
    thread.Start(); 
    while (are.WaitOne()) // main thread waits for the event to be signaled 
    { 
    Console.WriteLine(DateTime.Now); 
    } 
} 
+1

+1以確保完整性。 – 2010-08-13 16:38:41