using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int threadCount = 2; int semaphoreCount = 1; Semaphore semaphore = new Semaphore(semaphoreCount, semaphoreCount);
Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++)
{ threads[i] = new Thread(ThreadMain);
threads[i].Start(semaphore); } for (int i = 0; i < threadCount; i++)
{ threads[i].Join(); } Console.WriteLine("All threads finished");
Console.ReadLine();
}
static void ThreadMain(object o){ Semaphore semaphore = o as Semaphore; Trace.Assert(semaphore != null, "o must be a Semaphore type"); bool isCompleted = false; while (!isCompleted) { if (semaphore.WaitOne(600, false))
{ try { Console.WriteLine("Thread {0} locks the sempahore", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); } finally { semaphore.Release(); Console.WriteLine("Thread {0} releases the semaphore", Thread.CurrentThread.ManagedThreadId); isCompleted = true; }}else{Console.WriteLine("Timeout for thread {0}; wait again",Thread.CurrentThread.ManagedThreadId);}}}}}谁能给细致的讲讲语句的运行原理
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int threadCount = 2; int semaphoreCount = 1; Semaphore semaphore = new Semaphore(semaphoreCount, semaphoreCount);
Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++)
{ threads[i] = new Thread(ThreadMain);
threads[i].Start(semaphore); } for (int i = 0; i < threadCount; i++)
{ threads[i].Join(); } Console.WriteLine("All threads finished");
Console.ReadLine();
}
static void ThreadMain(object o){ Semaphore semaphore = o as Semaphore; Trace.Assert(semaphore != null, "o must be a Semaphore type"); bool isCompleted = false; while (!isCompleted) { if (semaphore.WaitOne(600, false))
{ try { Console.WriteLine("Thread {0} locks the sempahore", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); } finally { semaphore.Release(); Console.WriteLine("Thread {0} releases the semaphore", Thread.CurrentThread.ManagedThreadId); isCompleted = true; }}else{Console.WriteLine("Timeout for thread {0}; wait again",Thread.CurrentThread.ManagedThreadId);}}}}}谁能给细致的讲讲语句的运行原理
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货