日期:2014-05-16  浏览次数:20866 次

新手问下关于线程的一个问题
实际情况描述下,
  一批数据需要处理,每次从其中抓取一部分交给线程去处理(将数据分成几份,交给几个线程处理),这批数据处理完毕之后,自动抓取下一批数据,然后重复下去,直到全部完成。
   
  现在遇见的问题是,当线程把异步调用的方法执行完毕之后,线程状态自动变成了stopped状态。当下一批数据抓取到的时候,一旦调用start方法进行操作时,会出异常“线程正在运行或者已经停止,无法重新启动”。
  问下高手们,怎么避免这个情况发生?
   PS:我不想把线程Abort掉,然后再重新实例化新的,这样子效率太低,而且还太耗资源。

------解决方案--------------------
给你一个参考
    public static class X
    {
        private static System.Collections.Generic.Queue<object> queue;
        private static int queueLock;
        private static void run()
        {
            do
            {
                while (System.Threading.Interlocked.CompareExchange(ref queueLock, 1, 0) != 0) System.Threading.Thread.Sleep(0);
                object value = queue.Count != 0 ? queue.Dequeue() : null;
                queueLock = 0;
                if (value == null) break;
                try
                {
                    //数据你的处理
                }
                catch { }
            }
            while (true);
        }
        private static void start()
        {
            queue = new System.Collections.Generic.Queue<object>();
            queue.Enqueue(new object());//添加你的数据
            for (int threadCount = 10; threadCount != 0; --threadCount) new Thread(run).Start();
        }
    }