如何解决如果没有System.out.println,Java whiletrue循环永远不会结束
我有以下代码,其中ArrayList填充在其他Java类(即Thread)中(总是填充,我每次都检查过),然后在Main类中有问题的块while(是),而问题是,如果我注释或删除 System.out.println(IDS.size());
尽管线程负责完成我需要的信息,但直到所有线程完成后,我才能显示结果。这是while(true)块的原因。
public static ArrayList<String> IDS = new ArrayList<String>();
//this arraylist is filled in other classes correctly (each Thread add a element -> 10 in total)
//here is the problem
while (true) {
//if I comment the next system.out.println line
//the loop never ends and never breaks
System.out.println(IDS.size());
if(IDS.size()==10) {
break;
}
}
//when the array is filled with the 10 elements,I show all the info
for (int k = 0; k < impresoras.size(); k++) {
System.out.println(impresoras.get(k).ID);
}
我不知道为什么会这样,有人可以帮忙吗? 预先感谢。
解决方法
最后,我对线程使用join方法来避免while true循环。 因此,只有我必须调用下一个方法,然后对我的项目执行System.out.println,当所有线程结束其工作时,将打印该项目。
public static ArrayList<MyThread> threadList = new ArrayList<MyThread>();
public static void openFileAndCreateThreads(String fileName) {
String line = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] line_parts = line.split(";");
MyThread t= new MyThread(line_parts[0].trim(),line_parts[1],line_parts[2]);
threadList.add(t);
t.start();
}
for (int j=0;j<threadList.size();j++) {
try {
threadList.get(j).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。