2011-09-21 141 views
1

我有两个线程类“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(); 
    } 

} 
+0

线程是当他们可以同时运行/ independantly时才有用。让一个线程等待另一个线程是一种更复杂和更慢的方式,在没有线程的情况下做同样的事情。 –

回答

2

你需要学习如何有效地使用wait()notify()

参见:

+0

雅我需要学习,但任何解决方案?如何使一个线程等待? – Aniketh

+1

@Aniketh,只是谷歌“Java,生产者消费者的例子”。 – mrkhrts

+0

@Aniketh解决方案是:使用wait()和notify() – pap

1

怎么样使用BlockingQueue为1的容量?使用提供而不是添加,以便生产者线程被阻止。

您也可以考虑使用一个Semaphore一个许可证,使其成为一个互斥。

0

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

t1.run() 
t.join() 

t1时间结束后继续。

相关问题