2017-10-07 158 views
-2
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個線程同時執行這個方法來加速這個過程。這個線程安全嗎?這段代碼是否線程安全?

+2

還要看'wordsNearest'方法。 – Oleg

+0

如果我無法控制wordsNearest,我該如何讓這段代碼安全? – user697911

+1

不知道別的,唯一安全的方法是在調用'wordsNearest'時使用一個線程或在'word2vectors'上同步。 – Oleg

回答

2

您的代碼段將是線程安全的,如果滿足以下條件:

  1. word2vectors.wordsNearest(...)調用是線程安全的
  2. word2vectors數據結構創建和當前線程初始化。
  3. 沒有改變pools.execute通話和計算整理的數據結構。

如果wordsNearest不看其他數據結構,如果不改變word2vectors數據結構,那麼它是一個合理的假設它是線程安全的。但是,唯一可以肯定的是分析它

但是,這也是值得注意的是,你只能提交一個任務執行人。由於每個任務都是由單個線程運行的,因此您的代碼只能有效使用一個線程。要利用多線程,您需要將您的單個大任務分解爲多個小而獨立的任務;例如把10000次的重複循環的執行調用的外部...

+0

你可以把這個作爲一個例子,將它分成多個小任務? – user697911

+0

我已經告訴過你一種方法。再次閱讀我的答案。 –

+0

我用您的建議更新了我的代碼。看起來工作不安全。假設我無法控制word2vectors.wordsNearest,我怎樣才能使這個方法線程安全? – user697911