测试了你的代码,没发现你的状况,但我遇到新的状况:
1.+=操作的非原子性,导致输出结果大多是 "Bruce"或者"Magic",而非两个的合体
2.我加了lock锁,后状况正常
[C#] 纯文本查看 复制代码 internal class Program
{
private static string outString = "";
static void Main(string[] args)
{
var stuList = new List<Stu> {new Stu {StuName = "Magic"}, new Stu {StuName = "Bruce"}};
foreach (Stu name in stuList)
{
var thread = new Thread(delegate() { CreateLoginProcess(name); });
thread.IsBackground = true;
thread.Start();
}
Thread.Sleep(500);
Console.WriteLine(outString);
Console.ReadKey();
}
public static void CreateLoginProcess(Stu stu)
{
lock (outString)
{
outString += stu.StuName;
}
}
}
public class Stu
{
public string StuName { get; set; }
} |