java - 线程需要等待列表更新

标签 java multithreading synchronization

下面的类会在特定的时间间隔更新 map 。

public class CheckerThread extends Thread {

   private volatile HashMap<String, Integer> map = new HashMap<>();

   @Override
   public void run() {
           while (true) {
                updateMap();
           try {
             Thread.sleep(1000);
            }
           catch (InterruptedException e) {
             // Do something
            }
          }
    }

  private void updateMap() {
   HashMap<String, Integer> localMap = new HashMap<>();
   int count = 0;
     while (count < 10) {
        localMap.put(count + "a", count);
      count++;
     }
        this.map = localMap;
   }


   public Map<String, Integer> getMap() {
    return this.map;
   }
}

下面的类调用方法 getMap() 来获取 Map 。我需要确保在“CheckerThread”类中返回 map 之前列表已完全更新。该方法应该等到 map 更新。

public class GetterThread extends Thread {

 private final CheckerThread checkerThread;

 public GetterThread(final CheckerThread checkerThread) {
    this.checkerThread = checkerThread;
  }

  @Override
  public void run() {
       System.err.println(this.checkerThread.getMap());
    }
  }

另一个类 Main 创建线程。

public class MainThread extends Thread {
 public static void main(final String[] args) throws   InterruptedException {
  int i = 0;
  GetterThread[] getterThreads = new GetterThread[5];
  CheckerThread checkerThread = new CheckerThread();
  checkerThread.start();
   while (i < 5) {
      getterThreads[i] = new GetterThread(checkerThread);
      getterThreads[i].start();
      Thread.sleep(1000);
       i++;
    }
  }
 }
}

最佳答案

线程的想法是可以的,但还不够(其中大多数是因为线程在完成工作后不会返回任何内容......)如果您仍想使用线程,那么您将以等待结束/加入/通知方法...

您可以使用任务-->可调用来代替线程-->可运行

Callables 是类固醇上的线程,您可以在 ExecutorService 中执行它们,并等待作业完成,甚至得到一个结果,让您知道一切是否正常或不!!

以此为例并查阅文档以获取更多信息:

public class _Foo {

    public static void main(String... args) throws InterruptedException, ExecutionException {
        ExecutorService exService = Executors.newSingleThreadExecutor();
        FutureTask<Boolean> futureTask = new FutureTask<>(new MapCleaner());
        exService.execute(futureTask);
        System.out.println("Was everything ok??: " + futureTask.get());
    }
}

class MapCleaner implements Callable<Boolean> {
    @Override
    public Boolean call() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
        return System.currentTimeMillis() % 2 == 0;
    }
}

关于java - 线程需要等待列表更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43210085/

相关文章:

c++ - Boost Asio io_service 析构函数卡在 OS X 上

java - 将同步方法转换为非阻塞算法

cookies - Cookie 同步 : user id mapping between different cookie domains

java - 为什么 "synchronized"对多态没有作用

java - ActiveMQ - 无法加载 : class path resource [activemq. xml]

带回调的 Java 同步

java - 解密 AES-GCM 时遇到问题

java - 如果没有 Thread.sleep(...) 调用,线程代码将无法正常工作

java - 为什么我会陷入无限循环

java - 如何在不忽略拼写错误的情况下通过相似性比较字符串?