×

Discussion Board

Results 1 to 4 of 4
  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    2

    Problems with Thread.sleep()

    Hi,

    we started to develop games for mobiles, but we announced serious problems, that we couldn't solve properly. The main problem, is to force the program to wait, we always get the exception IllegalMonitorStateException, and the application doesn't wait. We tried Thread.sleep(), also, then more weird things happen, for example. The following code result in 1,5 second wait, and then a quick draw , why???

    g.drawImage(Image,10,10,0);
    try {Thread.sleep(500) catch (Exception e) {};

    g.drawImage(Image2,10,10,0);
    try {Thread.sleep(500) catch (Exception e) {};

    g.drawImage(Image3,10,10,0);
    try {Thread.sleep(500) catch (Exception e) {};

    We thought it would work like, draw the 1st image, then wait, draw 2nd image, wait and so on... but not... why?
    How can we solve this problem??

    Thx

    mobilgames.uw.hu

  2. #2
    Super Contributor
    Join Date
    Mar 2003
    Location
    Israel
    Posts
    2,280
    The effect you describe is not because of Thread.sleep(). It is because most phones have internal double buffering, so anything you draw in the paint() method, won't show up on screen until paint() returns.
    To get the effect you describe, you'll need to do something like:
    Code:
    int state;
    
    public void paint(Graphics g) {
      switch (state) {
        case 0:
          g.drawImage(Image,10,10,0);
          break;
        case 1:
          g.drawImage(Image2,10,10,0);
          break;
        case 2:
          g.drawImage(Image3,10,10,0);
          break;
      }
    }
    
    public void animate() {
      state = 0;
      repaint();
      try {Thread.sleep(500)} catch (Exception e) {};
      state = 1;
      repaint();
      try {Thread.sleep(500)} catch (Exception e) {};
      state = 2;
      repaint();
    }
    I haven't tested this code, but it may be necesary to add a call to serviceRepaints() after every repaint() to make sure that the paint events don't get stuck in the event queue.

    shmoove

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    2

    Thread

    thx shmoove, i'll try....

  4. #4
    Super Contributor
    Join Date
    Jun 2003
    Location
    Cheshire, UK
    Posts
    7,395
    You get an IllegalMonitorStateException when you're calling wait() because the thread calling wait() doesn't own the lock on the object on which you're wait()ing. You need to:

    synchronized (myObject) {
    myObject.wait();
    }

    As shmoove says, though, you're new problem is not related to sleep(), but to the handling of paint events, so switching to wait wouldn't help.

    Graham.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×