我有两个线程类“AddThread”和“ReadThread”。这些线程的执行应如下所示:“AddThread应该添加1条记录,并等待ReadThread显示该记录,之后ReadThread应该再次显示该添加的记录AddThread应该添加另一条记录”,此过程应该继续进行,直到添加了所有记录(REcords为从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();
    }

}

最佳答案

您将需要学习如何有效使用 wait() notify()

也可以看看:

  • Guarded Blocks
  • 09-13 08:57