有这样一个需求,有10个资源放在一个arraylist中,有3个线程(委托的函数一样)在抢这10个资源,每个线程抢到资源后将这个资源从arraylist中除去,当arraylist中无资源后,退出。最好能有一些跑的起来的程序给我示例下,谢谢各位大侠了!

解决方案 »

  1.   

    ArrayList list=new ArrayList();
    for(int i=0;i<10;i++)
    {
        list.Add(i);
    }for(int i=0;i<3;i++)
    {
       Thread thread=new Thread(new ThreadStart(Start));
       thread.IsBackground=true;
       thread.Start();
    }private void Start()
    {
       lock(this)
       {
          if(list[0]==null)
              return;
          string i=list[0].ToString();
          list.Remove(list[0]);
       }
    }应该有写对吧!关键是使用lock对象,像移除,添加,更新对象等操作在多线程中,就要使用lock,保证只有线程操作该对象,这样才不会报错。
      

  2.   

            private List<string> m_lstText = new List<string>();
            private List<string> m_lstNewText = new List<string>();
            private object objLock = new object();        private void button1_Click(object sender, EventArgs e)
            {
                m_lstText.Clear();
                m_lstNewText.Clear();
                for (int i = 0; i < 100; i++)
                {
                    m_lstText.Add(i.ToString());
                }            ThreadPool.QueueUserWorkItem(new WaitCallback(fun),"线程1");
                ThreadPool.QueueUserWorkItem(new WaitCallback(fun), "线程2");
                ThreadPool.QueueUserWorkItem(new WaitCallback(fun), "线程3");
            }        protected void fun(object o)
            {
                while (true)
                {
                    lock (objLock)
                    {
                        if (m_lstText.Count <= 0)
                            break;                    m_lstNewText.Add(o.ToString() + "  "+ m_lstText[0]);
                        m_lstText.RemoveAt(0);
                    }
                }
            }