2014-03-12 57 views
0

我希望线程等到上一个线程使用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(); 
         } 
+0

到目前为止,没有足够的信息。什么是'br'和'threadCount',这是如何调用和执行的,但是你可能想看看http://docs.oracle.com/javase/7/docs/api/java/util/ concurrent/CountDownLatch.html - 这是为了这个目的而创建的。 – Marco13

+0

我的猜测是你的线程在同一个br实例上不同步导致notifyAll()无法按照你期望的行为 – xea

+0

编辑代码 – user3409835

回答

0

要使用等待/通知,两个线程应该得到共享锁,都检查条件,并根据需要进行修改,如果你一定只会有1等待notify()是OK的线程,如果没有的话使用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(); 
} 
+0

给出问题的答案 – user3409835