使用Thread查找2个键的最小距离

时间:2017-09-28 07:09:13

标签: java multithreading

我在列表中有我的String键,从一组MainKey,我试图找到使用线程的最小距离。 因此,对于每个键,我必须遍历整个Set并记录距离。 我正确使用线程,因为在日志中我看到两个线程使用相同的密钥。

  public void matchKeys() {
    // read all MAin keys from redis

    Set<String> allKeys = redisTemplate.keys("*");
    // get the failure keys list 
    final List<String> FailureList = new ArrayList<>();
    FailureList.add("samsung5210e");
    FailureList.add("lgSL50");

   // thread to find the minimum distacne of all failure keys from the MainKeys list 
    Thread t = new Thread() {
        @Override
        public void run() {
            int Distance;

            for (String e : FailureList) {
                for (String s : allKeys) {
                    Distance = damerauLevenshteinDistancee(e), s);

                        LOG.log(Level.INFO, "Distance is {0} for Key {1} and the failure Key is {2}", new Object[]{Distance, s, e});


                }
            }

        }
    };
    t.start();

}

1 个答案:

答案 0 :(得分:0)

如果我的理解是正确的,距离计算成本很高,并且您正在尝试多线程,您应该做的事情如下:

for (String e : FailureList) {
    for (String s : allKeys) {
        Thread t = new Thread() {
            @Override
            public void run() {
                int distance = damerauLevenshteinDistancee(e), s);
                LOG.log(Level.INFO, "Distance is {0} for Key {1} and the failure Key is {2}", new Object[]{Distance, s, e});
            }
        }
        t.start();
    }
}