祝大家有美好的一天。
我有一个线程,如下所示,在其 while true 条件下,连续检查 HashSet 内的数据,如果存在,则提取这些数据并执行某些操作,以防 HashSet 中 5 分钟内没有符号(这是我的问题我怎样才能将这样的条件保留在下面的 else block 中是可能的)
package com;
import java.util.HashSet;
public class Tester extends Thread
{
HashSet<String> set = new HashSet<String>();
public void run() {
while (true) {
try {
if (set.size() > 0) {
// extract those and do something
set.clear();
}
else {
// if there were no elements in set for more than 5 minutes than execute a task
// here is my question , to keep such a check is possible or not
}
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
public static void main(String args[]) {
try {
Tester qT = new Tester();
qT.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
您可以在循环之前初始化时间戳。然后,如果 set.size() > 0
为 true,则将时间戳更新为当前时间。在 else 中,您检查保存的时间戳是否比当前时间戳至少早 5 分钟。
你可能想要这样的东西:
package com;
import java.util.HashSet;
import java.util.Date;
public class Tester extends Thread
{
HashSet<String> set = new HashSet<String>();
public void run() {
Date d = new Date();
while (true) {
try {
if (set.size() > 0) {
d = new Date();
set.clear();
}
else {
if(new Date().getTime() - d.getTime() > 300000){
d = new Date();
//execute your method
}
}
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
public static void main(String args[]) {
try {
Tester qT = new Tester();
qT.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于java - 当线程条件为 true 时,内部是否可以进行时间检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867109/