2014-01-25 2 views
-3

Этой программа работает в бесконечный цикл:что проблема в этом многопоточном коде

public class NewClass { 

    static void execute(String[] tasks) { 
     PCTest test = new PCTest(tasks); 
     new Thread(test.producer, "Prod").start();   
     new Thread(test.consumer, "Con").start(); 

    } 
    private static class PCTest { 

     private String currentTask; 
     final String[] producerTasks; 
     final Prod producer; 
     final Consmr consumer; 

     public PCTest(String[] producerTasks) { 
      this.producerTasks = producerTasks; 
      producer = new Prod(); 
      consumer = new Consmr(); 
     } 

     private class Prod implements Runnable { 

      Prod() { 
      } 

      public synchronized void run() { 
       int i = 0; 
       while (i < producerTasks.length) { 
        if (currentTask == null) { 
         currentTask = producerTasks[i++]; 
         this.notify(); 
        } 
        try { 
         this.wait(); 
        } catch (InterruptedException e) { 
         //do Nothing 
        } 

       } 
      } 
     } 

     private class Consmr implements Runnable { 

      Consmr() { 
      } 

      public synchronized void run() { 
       int i = 0; 
       while (i < producerTasks.length) { 
        if (currentTask != null) { 
         System.out.print(currentTask); 
         i++; 
         if (i < producerTasks.length) { 
          System.out.print(","); 
         } 
         currentTask = null; //* 
         this.notify(); 
        } 
        try { 
         this.wait(); 
        } catch (InterruptedException e) { 
         //do Nothing 
        } 
       } 
      } 
     } 
    } 


public static void main(String a[]){ 
    String ar[]={"a","b","c"}; 
    execute(ar); 
} 
} 
+0

Мы не знаем. В чем проблема? –

+3

Возможно, отладка расскажет вам больше об этом! –

+0

Вы должны предоставить более подробную информацию о том, что вы пытаетесь выполнить и что не работает должным образом. –

ответ

1

Из приведенной выше коды, кажется, ваши потоки в inifinite wait состояния. Поскольку функции wait() и notify() выполняются неправильно.

Ваша нить производителя установит currentTask и отправится ждать, позвонив по телефону this.wait(). Здесь this является экземпляром класса Prod. Ваш потребитель действительно делает this.notify(), но здесь this является экземпляром класса Consmr, и ваш потребитель также переходит в состояние inifinite wait.

Просто вы не notifying экземпляр, который другой поток waiting на

Надежда его ясно.

0

Это остановит бесконечный цикл, если вы меняете оба вызова из

this.wait() 

в

this.wait(50) 

Это довольно много хак, хотя.

Смежные вопросы