Chetan Chetan - 6 months ago 23
Java Question

About multi threading

How to kill the thread?
.....
How to restart them again in multi threading?

Answer

i wrap my worker threads up in their own class and use a terminated property to kill the thread proc loop.

sorry i dont have a java version to hand right now but you should get the idea from this http://pastie.org/880516

using System.Threading; 

namespace LoaderDemo
{
    class ParserThread
    {
        private bool m_Terminated;
        private AutoResetEvent m_Signal;
        private string m_FilePath;
        ...

        public ParserThread(AutoResetEvent signal, string filePath)
        {
            m_Signal = signal; 
            m_FilePath = filePath;

            Thread thrd = new Thread(this.ThreadProc);
            thrd.Start(); 
        }

        public bool Terminated { 
            set { m_Terminated = value; } 
        }

        private Guid Parse(ref string s)
        {
            //parse the string s and return a populated Guid object
            Guid g = new Guid();

            // do stuff...

            return g;
        }

        private void ThreadProc()
        {
            TextReader tr = null;
            string line = null;
            int lines = 0;

            try
            {
                tr = new StreamReader(m_FilePath);
                while ((line = tr.ReadLine()) != null)
                {
                    if (m_Terminated) break;

                    Guid g = Parse(ref line);
                    m_GuidList.Add(g);
                    lines++;
                }

                m_Signal.Set(); //signal done

            }
            finally
            {
                tr.Close();
            }

        }

    }
}