炫意html5
最早CSS3和HTML5移动技术网站之一

简单的线程问题

  static List<int> numberList = new List<int>();
static void Main(string[] args)
{
Thread thread1 = new Thread(() => Add(101,150));
Thread thread2 = new Thread(() => Add(151,200));
thread1.Start();
thread2.Start();
Thread.Sleep(1000);
StringBuilder sb = new StringBuilder();
foreach (var item in numberList)
{
sb.AppendFormat("\"{0}\",\r\n", item);
}
using (StreamWriter sw = new StreamWriter($"f:/{DateTime.Now.ToString("yyyyMMddHHmmsss")}.txt", false, Encoding.UTF8))
{
sw.Write(sb.ToString());
sw.Flush();
sw.Close();
sw.Dispose();
}
Console.WriteLine("Hello World!");
Console.ReadKey();
}
static void Add(int start,int end)
{
Mutex mutex = new Mutex();
if (mutex.WaitOne())
{
try
{
for (int i = start; i <= end; i++)
{
numberList.Add(i);
}
}
finally
{
mutex.ReleaseMutex();
mutex.Dispose();
}
}
}

----------------------------
多运行几次会报错,或者输出的数字不对

回答

static void Add(int start,int end)
{
Mutex mutex = new Mutex(); // 这个mutex不应该在函数中建立, 需要全局的
if (mutex.WaitOne())

炫意HTML5 » 简单的线程问题

Java基础教程Android基础教程