2015-02-10 68 views
-2

是否有任何可能的方式來填充列表或多個線程中的任何其他數據?線程的Java填充變量

我已經嘗試使用同步列表。

public class Main { 
    public static ArrayList<String> list = 
     Collections.synchronizedList(new ArrayList<String>()); 
    public static void main(String[] args) { 
     MyRunnable r = new MyRunnable(); 
     Thread t1 = new Thread(r); 
     t1.start(); 
     for(String s : list) 
      System.out.println(s); 
    } 
} 
public class MyRunnable implements Runnable { 
    @Override 
    public void run() { 
     Main.list.add("testing some code"); 
    } 
} 
+3

是的,有一個可行的辦法。其中一種可能的方法是使用同步列表。你的問題到底是什麼? – yole 2015-02-10 08:28:36

+0

同步列表位於Main類中。在運行線程並填充數據(使用某些字符串)後,從Main類訪問時列表仍爲空 – phantom13 2015-02-10 08:30:05

+4

請向我們顯示代碼。 – yole 2015-02-10 08:30:22

回答

2

使用線程時,您需要使用來自java.util.concurrent包的集合。它們更適合於同步集合,因爲它們提供了附加的原子方法,如用於映射的putIfAbsent

但是,這只是理論,你可以把一些代碼?

更新: 您的問題來自完成主線程之前您的MyRunnable完成。您需要添加

t1.join() 

這會告訴你的主類,以等待,直到MyRunnable線程結束。

+0

你不需要*來。同步集合可以工作(儘管他們沒有花哨的原子操作)。 – immibis 2015-02-10 08:37:32

+0

謝謝你確認我。 – laune 2015-02-10 08:42:51

+0

但榮幸是你的這個答案:) – Beri 2015-02-10 08:44:23

3

你有一個競賽條件。主程序在列表仍然爲空時打印列表。只有這樣,線程才能工作併爲其添加內容。

等待線程來完成:

t1.join(); 
// now print 
+0

感謝您的回答,真正有幫助 – phantom13 2015-02-10 08:39:12

+0

完美的作品:) – phantom13 2015-02-10 08:41:22