我有兩個線程類「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();
}
}
線程是當他們可以同時運行/ independantly時纔有用。讓一個線程等待另一個線程是一種更復雜和更慢的方式,在沒有線程的情況下做同樣的事情。 –