package com.gangwu.lucene.demo;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class LuceneThreadDemo {
public static void main(String[] args) {
try {
File file = new File("/root/data/02");
Directory directory = FSDirectory.open(file);
IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new StandardAnalyzer());
IndexWriter indexWriter = new IndexWriter(directory, config);
// final String[] values = {"common","term","new","term","term","term","common","term","common"};
final String[] values = {"1","2","3","4","5","6","7","8","9"};
Thread t1 = new Thread(new IndexThread(indexWriter, values, 0));
Thread t2 = new Thread(new IndexThread(indexWriter, values, 1));
t1.start();
t2.start();
//thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。
//比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
t1.join();
t2.join();
indexWriter.commit();
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class IndexThread implements Runnable {
IndexWriter indexWriter;
String[] values;
int start;
public IndexThread(IndexWriter indexWriter, String[] values, int start) {
this.indexWriter = indexWriter;
this.values = values;
this.start = start;
}
public void run() {
for (int i = start; i < values.length; i += 2) {
System.out.println("start run Thread " + i);
try {
Document document = new Document();
document.add(new TextField("title", values[i], Store.YES));
indexWriter.addDocument(document);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("-> end run Thread " + i);
}
}
}
Lucene系列 - 多线程下建立索引
最新推荐文章于 2021-02-13 12:33:48 发布