在等待初始化另一个变量时,如何执行执行某些操作的方法?

How can I execute a method that does something while I'm waiting for another variable to be initialised?

我想检查一个时间链接列表,看看它们是否在我的服务器没有从客户端获得连接时过期,或者甚至每隔一两分钟检查一次。我不完全确定这是如何实现的。我宁愿不必执行线程程序,但我知道我可能不得不这样做。我将不胜感激 feedback/advice 你们可以给我。

这是我对一些我愚蠢地认为可行的尝试

boolean connected = false;
       while(connection==null){
                System.out.println("before");
                connection = providerSocket.accept();
                System.out.println("after");
                user.checkForExpiredUsers();

            }

这是它在另一个class中调用的方法。

void checkForExpiredUsers(){
            String currentTime = new SimpleDateFormat("dd/MM/yy HH:mm:ss").format(new Date());

            for(int i =0; i<locationLat.size();i++){
                if(goodTimeDiff(currentTime,userTimeList.get(i))==false){
                    removeFromLists(i,locationLat,locationLong,destinationLat,destinationLong,userTimeList);
                    System.out.println("removed user");
                    System.out.println("The list of times: ");
                    System.out.println(userTimeList +"\n");
                }
            }

        }

也许我可以 运行 一个单独的 java 程序,只有一个调用此方法的主循环和 while 循环? 类似于:

while(true){user.checkForExpiredUsers();}

使用 java.util.concurrent 包中的并发实用程序是最简单的方法。


如果我理解正确,以下代码应该有所帮助:

    CountDownLatch latch = new CountDownLatch(1); // It's a barrier which holds the execution until it is counted down by another thread
    ExecutorService exec = Executors.newFixedThreadPool(2);
    exec.submit(new Runnable() { // Your first job which tries to get connection

        @Override
        public void run() {
            connection = providerSocket.accept();
            latch.countDown(); // necessary to signal that it's enough to wait
        }
    });
    exec.submit(new Runnable() { // Your worker job which performs the check

        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()) { // this is required for proper exit
                user.checkForExpiredUsers();
            }
        }
    });
    latch.await(); // Here the main thread will pause until a connection is acquired by the first job
    exec.shutdownNow(); // Stop our jobs by setting interrupted flag for them

创建每分钟执行一次任务的定时任务

public class ScheduledTask extends TimerTask {

   Date now; // to display current time

  // Add your task here
  public void run() {
        checkForExpiredUsers(); // run your code here
  }
}

主要是class

Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); 
time.schedule(st, 0, 10000); // Create Repetitively task for every 10 secs