要減少Thread.sleep
的等待時(shí)間,您可以考慮以下方法:
Thread.sleep(1000)
更改為Thread.sleep(1000000)
,這將使等待時(shí)間減少10倍。try {
Thread.sleep(1000000); // 1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
java.util.concurrent
包中的高級同步工具,例如ScheduledExecutorService
,它可以更精確地控制任務(wù)的執(zhí)行時(shí)間。import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> {
System.out.println("Task executed");
}, 1, 1, TimeUnit.SECONDS);
}
}
ScheduledExecutorService
,可以考慮使用java.util.Timer
類。import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task executed");
}
};
timer.schedule(task, 1000, 1000); // 延遲1秒,然后每隔1秒執(zhí)行一次
}
}
請注意,減少Thread.sleep
的等待時(shí)間可能會(huì)導(dǎo)致線程調(diào)度和資源競爭問題。在實(shí)際應(yīng)用中,請確保仔細(xì)考慮這些因素,并根據(jù)您的需求和系統(tǒng)資源選擇合適的方法。