實例線程池:System.Threading.ThreadPool vs Semaphore?
public class Example {
public static void Main() {
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 1
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 2
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); //task 3
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
static void ThreadProc(Object stateInfo) {
Console.WriteLine("Hello from the thread pool.");
}
}
例信號燈:
public class Example
{
private static Semaphore _pool;
private static int _padding;
public static void Main()
{
_pool = new Semaphore(0, 3);
// Create and start five numbered threads.
//
for(int i = 1; i <= 5; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));
t.Start(i);
}
Thread.Sleep(500);
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(3);
Console.WriteLine("Main thread exits.");
}
private static void Worker(object num)
{
Console.WriteLine("Thread {0} begins " +
"and waits for the semaphore.", num);
_pool.WaitOne();
int padding = Interlocked.Add(ref _padding, 100);
Console.WriteLine("Thread {0} enters the semaphore.", num);
Thread.Sleep(1000 + padding);
Console.WriteLine("Thread {0} releases the semaphore.", num);
Console.WriteLine("Thread {0} previous semaphore count: {1}",
num, _pool.Release());
}
}
我想它的一些開銷的信號燈,在這個例子中創建5個線程, 但線程池,使用內置的「線程池「(它將使用像backgroundworker這樣的現有線程)。這是正確的還是更多,是否有任何真正的優勢使用信號量,如果你只是想要一個簡單的線程池,但速度和性能是一個問題?
我想補充一點,如果一個線程崩潰,如果你使用的ExecutorService,這將產生一個新的線程返回線程數量(這取決於執行程序類型)。另一方面,如果您手動創建線程,則必須對其進行管理。 – Adrian