我目前正在编写一个Java程序,该程序从html获取源代码并对其进行解析以获取值。正常工作正常,但是一旦我尝试让它在while循环中运行并每30秒重新获取数据,我的PC速度就会变慢,直到我手动停止程序为止。
while(true) {
try {
URL url = new URL("https://www.reddit.com/r/gaming/");
URLConnection urlConn = url.openConnection();
System.out.println(urlConn.getContentType()); //it returns text/html
BufferedReader in = new BufferedReader
(new InputStreamReader(urlConn.getInputStream()));
File test = new File("test");
BufferedWriter writer = new BufferedWriter(new FileWriter(test));
String text;
while ((text = in.readLine()) != null) {
writer.write (text);
}
writer.close();
in.close();
String content = new String(Files.readAllBytes(Paths.get("test")), "UTF-8");
Pattern pattern = Pattern.compile("title=(.*?)\">");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
System.out.println(matcher.group(1));
if (Integer.valueOf((matcher.group(1))) <= 99999999) {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("alert.wav"));
clip.open(inputStream);
clip.start();
}
}
Thread.sleep(30000);
} catch (MalformedURLException f) {
f.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
} catch (InterruptedException f) {
f.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
任何提示为何会发生这种情况?
答案 0 :(得分:2)
也许我对代码有误解,但是我认为Thread.sleep()
仅在您不抛出时才运行。我认为您想将其放在try / catch之外,这样,如果失败,则等待30秒再尝试。否则,如果某个原因导致throw
,您将立即重试,由于自上次尝试以来什么都没有真正改变,因此您将一遍又一遍地立即throw
。
现在,您的代码是:
while (true) {
try {
// Do a lot of things that can throw
if(something_bad_happens) throw new Error();
/*
* This sleep will only be reached
* if we don't throw
*/
Thread.sleep(30000);
} catch (errors) {
// Deal with errors
}
}
我认为您实际上想要这个:
while (true) {
try {
// Do a lot of things that can throw
if(something_bad_happens) throw new Error();
} catch (errors) {
// Deal with errors
}
// Always sleep between attempts no matter what
Thread.sleep(30000);
}