0

I am new in java Android... I am trying to create two threads (named: Clean and Progress) that will run two different methods each method get the same object mix.while Clean will run a time consuming method that is part of mix's class (mix.TimeConsumingMethod();) I want Progress thread to monitor the progress of TimeConsumingMethod() by checking class variables such as mix.length and mix.framesClean

in progress I check to see mix.length > 0 if not I want Progress to wait over here my app crashes and in log CAT i get an error of:

09-20 10:37:32.773: E/AndroidRuntime(12030): java.lang.IllegalMonitorStateException: object not locked by thread before wait()

snippet of code invoking both threads:.

    mix = new MixMaxMain(); 

    progressThread = new Thread(new Runnable() {

      @Override
      public void run() {
        Progress (mix);
      }
    },"Progress Thread");

    CleanThread = new Thread(new Runnable() {

        @Override
        public void run() {
            Clean (mix);
        }
    },"Cleaner Thread");

    Log.d("STOP", "SEnding cleanThread AND progress Thread");
    CleanThread.start();
    progressThread.run();

snippet of Clean running time consuming method:

    long time_start = SystemClock.elapsedRealtime();        
    mix.Run(Daudio,mu,sigSqr,c);
    long time_end = SystemClock.elapsedRealtime();

snippet of Progress:

      while(mix.length==0) {try {
      Log.d("Progress", "Length is Zero");
    Thread.sleep(1);//fails here!!
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} }
  Log.d("Progress", "Clean Has Started");
  int totalProgressLen = (int)(mix.length+0.7*mix.length);

  while(mix.done==false)
  {
      try {
          progressThread.wait(50);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      progress.setProgress(mix.framsClean*256/totalProgressLen  );
  }
parsley72
  • 8,449
  • 8
  • 65
  • 98
Hillel
  • 301
  • 1
  • 11
  • You need to lock the object before calling wait. http://stackoverflow.com/questions/661068/threading-in-java-how-to-lock-an-object – Atuos Oct 04 '14 at 08:50

1 Answers1

0

You get the IllegalMonitorStateException if the thread you're calling wait on does not own the lock on the monitor you're calling it on.

To do this, you can surround the wait() call in a synchronized block. In your case, it would be something like:

synchronized(progressThread){
    progressThread.wait(50);
}

There is also a way to check for this with the holdsLock(Object obj) method, which will return true only if the current thread holds the monitor lock on the specified object.

For full details, take a look at the Java Documentation on wait() for an Object.

SBerg413
  • 14,515
  • 6
  • 62
  • 88