2011-09-21 140 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時間結束後繼續。

相關問題