Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8808971
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T02:45:18+00:00 2026-06-14T02:45:18+00:00

I’m trying to learn how to pause and resume a thread in java. I’m

  • 0

I’m trying to learn how to pause and resume a thread in java. I’m using an Applet that implements Runnablehas 2 buttons “Start” and “Stop”.

public void init(){
  th = new Thread(this);
  th.start();

  btn_increment = new Button("Start");
  btn_increment.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ev){
      th.notify();
    }
  });
  add(btn_increment);

  btn_decrement = new Button("Stop");
  btn_decrement.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ev){
      try{
        th.wait();
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }
  });

  add(btn_decrement);                               
}

The run method of the thread:

public void run(){
  while(true){
    repaint();
    try{
      Thread.sleep(20);
    } catch(InterruptedException e) {
      e.printStackTrace();
    }
  }
}

Now whenever I try to to pause or resume the thread an exception is thrown:

Exception in thread "AWT-EventQueue-1" java.lang.IllegalMonitorStateException

Notes:

The previous code runs perfectly if I use the deprecated methods suspend() and resume(), but the documentation points out at using notify() and wait() instead with synchronization. I tried adding the word synchronized to the actionPerformed method, but it still throws the exception.

Can someone please explain WHY this isn’t working and how to solve the synchronization problem? Few explanation points would really be of much help 😉

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T02:45:19+00:00Added an answer on June 14, 2026 at 2:45 am

    You have misunderstood how wait() works. Calling wait on a Thread object does not pause that thread; it instead tells the currently running thread to wait for something else to happen. To explain why, I’ll need to back up a bit and explain what synchronized actually does.

    When you enter a synchronized block you obtain the monitor associated with an object. For example,

    synchronized(foo) {
    

    obtains the monitor associated with the object foo.

    Once you have the monitor, no other threads can obtain it until you exit the synchronized block. This is where wait and notify come in.

    wait is a method on the Object class that tells the currently running thread to temporarily release the monitor it holds. This allows other threads to synchronize on foo.

    foo.wait();
    

    This thread will not resume until someone else calls notify or notifyAll on foo (or the thread is interrupted). Once that happens, this thread will attempt to re-acquire the monitor for foo and then continue. Note that if any other threads are waiting to obtain the monitor then they might get in first – there is no guarantee of the order the JVM will hand out locks. Note that wait() will wait forever if no-one calls notify or notifyAll. It’s usually best to use the other form of wait that takes a timeout. That version will wake up when someone calls notify/notifyAll or when the timeout has expired.

    So, you need one thread to do the waiting and a different thread to do the notifying. Both wait and notify must hold the monitor on the object they are trying to wait on or notify; this is why you are seeing the IllegalMonitorStateException.

    An example might help you understand:

    class RepaintScheduler implements Runnable {
        private boolean paused = false;
        private final Object LOCK = new Object();
    
        public void run() {
            while (true) {
                synchronized(LOCK) {
                    if (paused) {
                        try {
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        repaint();
                    }
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public void pause() {
            synchronized(LOCK) {
                paused = true;
                LOCK.notifyAll();
            }
        }
    
        public void resume() {
            synchronized(LOCK) {
                paused = false;
                LOCK.notifyAll();
            }
        }
    }
    

    Your Applet code can then do this:

    public void init() {
        RepaintScheduler scheduler = new RepaintScheduler();
        // Add listeners that call scheduler.pause and scheduler.resume
        btn_increment.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
            scheduler.resume();
        }});
        btn_decrement.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
            scheduler.pause();
        }});
        // Now start everything up
        Thread t = new Thread(scheduler);
        t.start();
    }
    

    Note that the Applet class does not care about how the scheduler pauses/resumes and does not have any synchronized blocks.

    So a possible sequence of events here is:

    • Thread A starts running the repaint scheduler.
    • Thread A goes to sleep for 20ms.
    • Thread B (the event dispatch thread) receives a button click; calls ‘pause’.
    • Thread B obtains the monitor on LOCK.
    • Thread B updates the ‘paused’ variable and calls LOCK.notifyAll.
    • No threads are waiting on LOCK so nothing interesting happens.
    • Thread B releases the monitor on LOCK.
    • Thread A wakes up, goes through its loop again.
    • Thread A obtains the monitor on LOCK.
    • Thread A sees that it should be paused, so it calls LOCK.wait.
    • At this point Thread A suspends, waiting for someone to call notifyAll. Thread A releases the monitor on LOCK.
    • Some time later, the user clicks ‘resume’.
    • Thread B calls scheduler.resume.
    • Thread B obtains the monitor on LOCK.
    • Thread B updates the ‘paused’ variable and calls LOCK.notifyAll.
    • Thread A sees the ‘notifyAll’ and wakes up. It tries to obtain the monitor on LOCK but it is held by Thread B so Thread A blocks.
    • Thread B releases the monitor on LOCK.
    • Thread A obtains the monitor and carries on.

    Does that all make sense?

    Having a separate LOCK variable is not required; I’ve done that to highlight the fact that you are not calling wait/notify on a Thread instance. Similarly, the logic inside the RepaintScheduler is not ideal but is just there to illustrate how wait/notify could be used.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I have thousands of HTML files to process using Groovy/Java and I need to
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.