private static final Word2Vec word2vectors = getWordVector();
private static Word2Vec getWordVector() {
String PATH;
try {
PATH = new ClassPathResource("models/word2vec_model").getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
log.warn("Loading model...");
return WordVectorSerializer.readWord2VecModel(new File(PATH));
}
ExecutorService pools = Executors.newFixedThreadPool(4);
long startTime = System.currentTimeMillis();
List<Future<?>> runnables = new ArrayList<>();
if (word2vectors != null) {
for (int i = 0; i < 3000; i++) {
MyRunnable runnable = new MyRunnable("beautiful", i);
runnables.add(pools.submit(runnable));
}
}
for(Future<?> task: runnables){
try {
task.get();
}catch(InterruptedException ie){
ie.printStackTrace();
}catch(ExecutionException ee){
ee.printStackTrace();
}
}
pools.shutdown();
static class MyRunnable implements Runnable{
private String word;
private int count;
public MyRunnable(String word, int i){
this.word = word;
this.count = i;
}
@Override
public void run() {
Collection<String> words = word2vectors.wordsNearest(word, 5);
log.info("Top 5 cloest words: " + words);
log.info(String.valueOf(count));
}
}
的word2vectors.wordsNearest()是从公共图书馆的方法。我打算让4个线程同时执行这个方法来加速这个过程。这个线程安全吗?这段代码是否线程安全?
还要看'wordsNearest'方法。 – Oleg
如果我无法控制wordsNearest,我该如何让这段代码安全? – user697911
不知道别的,唯一安全的方法是在调用'wordsNearest'时使用一个线程或在'word2vectors'上同步。 – Oleg