最近我一直在使用大数字循环打印出来Hello World:
int counter = 0;
while(true) {
//loop for ~5 seconds
for(int i = 0; i < 2147483647 ; i++) {
//another loop because it's 2012 and PCs have gotten considerably faster :)
for(int j = 0; j < 2147483647 ; j++){ ... }
}
System.out.println(counter + ". Hello World!");
counter++;
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个非常愚蠢的方法,但我还没有在Java中使用任何计时器库.怎么会修改上面打印每说3秒?
在NetBeans中,有一个新提示:Thread.sleep在循环中调用.
问题1:如何/何时在循环中睡觉是一个问题?
问题2:如果这是一个问题,我该怎么做?
更新:问题3:这是一些代码.在这种情况下告诉我,如果我应该在循环中使用其他东西而不是Thread.Sleep.简而言之,这是由侦听客户端TCP连接的服务器使用的.此处使用睡眠以防达到与客户端的最大会话数.在这种情况下,我希望应用程序等到免费会话可用.
public class SessionManager {
private static final int DEFAULT_PORT = 7500;
private static final int SLEEP_TIME = 200;
private final DatabaseManager database = new DatabaseManager();
private final ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT);
public SessionManager() throws IOException, SQLException
{
}
public void listen()
{
while (true)
if (Session.getSessionCount() < Session.getMaxSessionCount())
try
{
new Thread(new Session(database, serverSocket.accept())).start();
}
catch (IOException ex) { ex.printStackTrace(); }
else
try
{
Thread.sleep(SLEEP_TIME);
}
catch (InterruptedException ex) { ex.printStackTrace(); …Run Code Online (Sandbox Code Playgroud) 伙计们如何处理这样的代码和警告?
private void listenOnLogForResult() {
String logs = "";
int timeCounter = 1;
while (logs.isEmpty()) {
try {
timeCounter++;
Thread.sleep(2000); // Wait 2 seconds
} catch (InterruptedException e) {
log.error(e.getLocalizedMessage(), e);
}
if (timeCounter < 30) {
logs = checkLogs()
} else {
logs = "Time out";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要暂停当前线程 2 秒钟以等待文件被填充,但我的 Intelij 在这里出现了问题。
而且我从声纳中收到错误:SonarLint:重新中断此方法或重新抛出“InterruptedException”。
我已经尝试过很多ExecutorService,但它总是在单独的线程中运行,我需要暂停当前的线程。
请帮忙..