[英]Looping thread arraylist
我在String数组上有一个简单的循环,然后将String传递给threadlist方法。 但是我似乎无法同时打印出两个String。 它只是打印第二个名称"Fred"
,这使我认为我正在用第二个String覆盖第一个String。 如何使ArrayList
包含字符串"Tim"
和"Fred"
?
import java.util.ArrayList;
public class Threads extends Thread implements Runnable{
private ArrayList threadList;
private String e;
public static void main(String[] args) {
String[] elements = {"Tim","Fred"};
Threads t = new Threads();
for (String e: elements) {
t.threadL(e);
}
//loop over the elements of the String array and on each loop pass the String to threadL
for (int index = 0;index<t.threadList.size();index++){
System.out.print(t.threadList.get(index));
}
//loop over the threadList arraylist and printout
}
public ArrayList<String> threadL(String e) {
threadList = new ArrayList<>();
threadList.add(e);
return(threadList);
}
}
解决问题的直接方法是,每次调用方法threadL
时都要实例化threadList
变量。 因此,在第二次调用中,将忽略之前存储的任何内容,并添加新内容:
public ArrayList<String> threadL(String e) {
threadList = new ArrayList<>(); // <-- instantiates a new list each time it is called
threadList.add(e);
return threadList;
}
您只能实例化该列表一次,例如在声明它的位置。 另外,您绝对不应该使用像List
这样的原始类型,而应始终使用键入的版本:
private List<String> threadList = new ArrayList<>();
请注意,在给定的示例中,实际上您没有使用任何Thread
或Runnable
功能(因为您没有覆盖run()
或启动了线程)。 另外, 与扩展Thread
, 更喜欢实现Runnable
。
每次循环时,您都将实例化一个新的数组列表。 这就是为什么您看不到element [0]的原因,因为它已被新列表替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.