java - 当线程条件为 true 时,内部是否可以进行时间检查

标签 java multithreading

祝大家有美好的一天。

我有一个线程,如下所示,在其 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/

相关文章:

java - 尝试设置数据绑定(bind)时出错

multithreading - 进程、线程、绿色线程、原型(prototype)线程、纤维、协程 : what's the difference?

java - ThreadPoolExecutor 的提交和执行方法有什么区别

java - 从远程 EJB 方法返回返回类型的父类(super class)

JavaFX:如何从其他类访问UI线程组件

multithreading - 并发软件中的读写实例

c++ - 如何中断 libfcgi 中的 Accept 方法?

java - java中内存使用量最小的Native Collection

java - 将 java 对象从 javascript 传递到 java

java - 尝试通过 kubernetes DNS 访问 kubernetes pod 时连接被拒绝