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