2011-05-21 82 views
-1

我爲每個文件創建了線程。下面給出了線程。在java中,如何在動態創建時處理線程

ALIST是一個數組列表中包含文件名{test1.txt,test2.txt,test3.txt}

for(String str : AList){ 

    thread t = new Thread(new Filechange(str)); 
    t.start(); 

    } 

Filechange類如下。

public class C implements Runnable { 

    private String tmp; 


    public Filechange(String strg) { 
    this.tmp = strg; 
    } 

    public void run() { 

    system.out.println("File Name ::"+tmp); 

    } t.sleep(1000); 
    t.run(); 


    } 

運行此代碼時,總是得到輸出"File Name ::test3.txt"。 如何解決這個問題?

+2

您在發佈代碼時犯了錯誤。請更正 – 2011-05-21 10:53:43

+1

該發佈代碼是否可以編譯?你的主要方法在哪裏? – 2011-05-21 10:53:54

+1

這不能是你真正的代碼(它不會編譯)。請發佈您的實際代碼。 – MByD 2011-05-21 10:54:14

回答

1

如何製作線索列表或其他?我認爲,當你重新分配「線程t」時,你將覆蓋前一個線程,因此,只有最後一個線程才能存活。做這樣的事情:

List<Thread> threadList = new ArrayList<Thread>(); 
for(String str : AList){ 

    threadList.add(new Thread(new Filechange(str))); 
    threadList.get(threadList.size()-1).start(); 

} 
+0

只能通過重新分配變量來「覆蓋」線程。線程對象一直保留到線程完成。 – OpenSauce 2011-05-21 11:05:44

+0

我會將新創建的線程分配給局部變量而不是'threadList.get ...'調用。它會更容易閱讀。 – Howard 2011-05-21 11:07:46