线程不等待

相对论

请参见下面的代码。我不会始终把main中的“ Count”始终设置为“ 5”。有人可以帮忙吗。

    class Program
{
    private static void Main(string[] args)
    {
        Thread t1 = new Thread(() => new Test("a"));
        Thread t2 = new Thread(() => new Test("b"));
        Thread t3 = new Thread(() => new Test("c"));
        Thread t4 = new Thread(() => new Test("d"));
        Thread t5 = new Thread(() => new Test("e"));

        t1.Start();
        t2.Start();
        t3.Start();
        t4.Start();
        t5.Start();

        t1.Join();
        t2.Join();
        t3.Join();
        t4.Join();
        t5.Join();

        Console.WriteLine(Test.Names.Count);
    }
}

public class Test
{
    public static ListClass<string> Names { get; set; }

    public Test(string name)
    {
        Console.WriteLine(name);
        //Thread.Sleep(10);
        if (Names == null)
            Names = new ListClass<string>();
        Names.Add(name);
    }
}

public class ListClass<T>
{
    private List<T> mylist = new List<T>();
    private object myLock = new object();

    public void Add(T item)
    {
        lock (myLock)
        {
            mylist.Add(item);
        }
    }

    public int Count
    {
        get { return mylist.Count; }
        private set
        { }
    }
}
巴伏

竞争条件很可能会发生,这意味着在线程检查Names是否为null的时间之间,另一个线程已经对其进行了初始化,因此将其覆盖,从而减少了作为新集合的计数。

在空检查周围放一个锁,或者在测试类中使用静态构造函数初始化集合,这不是最好的解决方案,但是会起作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章