如何让一个线程等待并执行另一个???

时间:2011-09-21 12:48:40

标签: java multithreading

我有两个Threads类“AddThread”和“ReadThread”。这些线程的执行应该是这样的“AddThread应该添加1条记录并等待ReadThread显示记录之后,ReadThread应该再次显示添加的记录AddThread应该添加另一条记录”这个过程应该继续,直到所有记录都被添加(记录是从LinkedList访问)。这是代码

class AddThread extends Thread
{
    private Xml_Parse xParse;

    LinkedList commonlist;

    AddThread(LinkedList commonEmpList)
    {
        commonlist = commonEmpList;     
    }

    public void run()
    {
        System.out.println("RUN");
        xParse=new Xml_Parse();
        LinkedList newList=xParse.xmlParse();       
        try
        {
            synchronized (this) {
            if(newList.size()>0)
            {
                for(int i=0;i<newList.size();i++)
                {
                    System.out.println("FOR");
                    commonlist.add(newList.get(i));
                    System.out.println("Added" +(i+1)+ "Record");

                }
                System.out.println(commonlist.size());
            }
            }
        }
        catch(Exception e)
        {

        }
    }
}



class ReadThread extends Thread
{
    LinkedList commonlist;

    ReadThread(LinkedList commonEmpList)
    {
        commonlist = commonEmpList;     
    }
    public void run()
    {
        try
        {
            synchronized (this) {


            System.out.println();
            System.out.println("ReadThread RUN");
        sleep(1000);
        //System.out.println("After waiting ReadThread RUN");
        System.out.println(commonlist.size());
            if(commonlist.size()>0)
            {
                for(int j=0;j<commonlist.size();j++)
                {
                System.out.println("Read For");
                System.out.println("EmpNo: "+((EmployeeList)commonlist.get(j)).getEmpno());
                System.out.println("EmpName: "+((EmployeeList)commonlist.get(j)).getEname());
                System.out.println("EmpSal: "+((EmployeeList)commonlist.get(j)).getEmpsal());

                }
            }
            }
    }
    catch(Exception e)
    {

    }
    }
}


public class MainThread
{
    public static LinkedList commonlist=new LinkedList();

    public static void main(String args[])
    {       
        AddThread addThread=new AddThread(commonlist);
        ReadThread readThread=new ReadThread(commonlist);
        addThread.start();
        readThread.start();
    }

}

3 个答案:

答案 0 :(得分:2)

您需要了解如何有效使用wait()notify()

另见:

答案 1 :(得分:1)

使用容量为1的BlockingQueue怎么样?使用offer而不是add来阻止生产者线程。

您也可以考虑将Semaphore与一个许可一起使用,使其成为互斥锁。

答案 2 :(得分:0)

您使用join()yield()来控制流量。如果您希望当前线程停止并等待新线程完成工作,

t1.run()
t.join()

当t1结束时继续。