线程等待最后一个通知它们

时间:2014-03-12 09:31:12

标签: java multithreading wait notify

我希望线程等到最后一个使用br并通知其他线程。但它首先进入wait(),我错过了什么?

public class CrawlerThread implements Runnable {
private BufferedReader br;
private FileHandler fileHandler;
private File sourceFile;
private String skillString;
private Map<String, String> urlData = new HashMap<String, String>();
private String urlFirst = Initializer.urlFirst;

public static Integer threadCount = 0;

public CrawlerThread(BufferedReader br, FileHandler fileHandler,
        File sourceFile, String skillString, Map<String, String> urlData) {
    this.br = br;
    this.fileHandler = fileHandler;
    this.sourceFile = sourceFile;

    this.skillString = skillString;
    this.urlData.putAll(urlData);
    new Thread(this).start();
}

@Override
public void run() {
    System.out.println("!!!!");

    String companyName;
    String searchString;
    SearchObject searchObject = new SearchObject();
    try {String c;
        while ((c=br.readLine())!=null && c.equalsIgnoreCase("Company Name")) {
            try {
                if ((companyName = br.readLine().trim()) != null) {
                    if (threadCount == (Initializer.MAX_THREAD - 1)) {
      synchronized(br){
                        System.out.println("++");
                        br.close();
                        br.notifyAll();}

                    } else
                        try {
                            System.out.println("**" + threadCount);
                            synchronized (br) {
                                synchronized (threadCount) {
                                    threadCount++;
                                }
                                br.wait();
                            }
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

1 个答案:

答案 0 :(得分:0)

要使用wait / notify,两个线程都应获取共享锁,并检查条件并在必要时进行修改,如果您确定只有1个线程正在等待notify()即可,如果没有则使用notifyAll(),基本上等待的线程应该像:

示例等待线程条件:

synchronized(lock){
  while(!condition){
    lock.wait();
  }
}

示例通知程序线程:

synchronized(lock){
  condition=true;
  lock.notifyAll();
}

您还可以使用CountDownLatch

final CountDownLatch latch=new CountDownLatch(1);

等待线程:

public void waitForCondition(){
  latch.await();
}

通知程序线程:

public void notifyWaitingTreads(){
  latch.countDown();
}