Home java Using wait () throws an IllegalMonitorStateException

Using wait () throws an IllegalMonitorStateException

Author

Date

Category

As far as I understand, the error is that either the stream includes objects that are not marked as synchronized or (possibly – and) if such an object changes while wait , then after the end of wait, this thread can use the object changed from another (in my case – ui) thread. But who, then, to mark as synchronized , whether it is necessary at all, and why everything works if you do not use wait is not clear.

Code:

public class MainActivity extends Activity {
public boolean cycleShouldContinue;
public int counter;
TextView currentCountTextView;
Thread thread;
@Override
public void onCreate (Bundle savedInstanceState) {
  super.onCreate (savedInstanceState);
  setContentView (R.layout.activity_main);
  currentCountTextView = findViewById (R.id.currentCount);
  cycleShouldContinue = true;
  iterationCycle ();
}
synchronized public void iterationCycle () {
  Runnable runnable = new Runnable () {
    @Override
    public void run () {
      while (cycleShouldContinue) {
        counter ++;
        runOnUiThread (new Runnable () {
          @Override
          public void run () {
            currentCountTextView.setText (String.valueOf (counter));
          }
        });
        try {
          thread.wait (1000);
        } catch (InterruptedException e) {
          e.printStackTrace ();
        }
      }
    }
  };
  thread = new Thread (runnable);
  thread.start ();
}

In general, the goal is to make an explicit instance of Thread so that you can refer to it and call its methods from elsewhere in the program. (After all, you can describe a new stream as if you did not allocate a name to it, but you can also apply only once, I wonder what it is called:

new Thread (new Runnable () {
    @Override
    public void run () {
    }
  }). start ();

Here here it is advised in the first answer to create an additional blocker class of some kind, but how it is attached to my thread, or do I need to inherit this class from Thread or whatever, I don’t understand anything at all.


Answer 1, authority 100%

The wait is method of the synchronized block must be called because the synchronized method uses a different monitor.

synchronized (thread) {
  try {
    thread.wait (1000);
  } catch (InterruptedException e) {
    e.printStackTrace ();
  }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions