簡體   English   中英

多線程Java

[英]Multi Threading Java

在我的程序中,我基本上有一個類似於的方法:

for (int x=0; x<numberofimagesinmyfolder; x++){
    for(int y=0; y<numberofimagesinmyfolder; y++){
        compare(imagex,imagey);
        if(match==true){
            System.out.println("image x matches image y");
        }
    }
}

所以基本上我有一個圖像文件夾,我比較所有圖像組合...所以比較圖像1與所有圖像,然后圖像2 ......等等。 我的問題是在搜索什么圖像匹配時,需要很長時間。 我試圖多線程這個過程。 有沒有人知道如何做到這一點?

不是每次都比較圖像,而是散列圖像,保存散列,然后比較每對消息的散列。 由於哈希值要小得多,因此可以更多地放入內存和緩存中,這樣可以顯着加快比較速度。

也許有一種更好的方法來搜索相等性,但一種選擇是將所有哈希值粘貼到一個數組中,然后按哈希值對它們進行排序。 然后迭代列表,查找相等的相鄰條目。 這應該是O(n*log(n))而不是O(n^2)就像您當前的版本一樣。

  1. 內環應該從y = x + 1開始,以利用對稱性。
  2. 首先將所有圖像加載到內存中。 不要從磁盤進行全部比較。
  3. 使用Java ExecutorService(基本上是一個線程池)。 所有索引組合的隊列任務。 讓線程將索引組合從任務隊列中拉出並執行比較。

以下是執行多線程的一些通用代碼:

public static class CompareTask implements Runnable {
    CountDownLatch completion;
    Object imgA;
    Object imgB;

    public CompareTask(CountDownLatch completion, Object imgA, Object imgB) {
        this.completion = completion;
        this.imgA = imgA;
        this.imgB = imgB;
    }

    @Override
    public void run() {
        // TODO: Do computation...

        try {
            System.out.println("Thread simulating task start.");
            Thread.sleep(500);
            System.out.println("Thread simulating task done.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        completion.countDown();
    }
}

public static void main(String[] args) throws Exception {
    Object[] images = new Object[10];

    ExecutorService es = Executors.newFixedThreadPool(5);

    CountDownLatch completion = new CountDownLatch(images.length * (images.length - 1) / 2);

    for (int i = 0; i < images.length; i++) {
        for (int j = i + 1; j < images.length; j++) {
            es.submit(new CompareTask(completion, images[i], images[j]));
        }
    }

    System.out.println("Submitted tasks. Waiting...");
    completion.await();
    System.out.println("Done");

    es.shutdown();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM