Jump to content

Java threads, a little help please :)

- - - - -

  • Please log in to reply
6 replies to this topic

#1
dusch

dusch

    Newbie

  • Members
  • Pip
  • 4 posts
I need implementation of methods suspend() and resume(), using wait() and notify(), but without using active waiting.

#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
What do you have so far?

#3
dusch

dusch

    Newbie

  • Members
  • Pip
  • 4 posts
I don't have anything, that is a homework task..
It supposed to be as simple as possible..
And, it's for tomorrow, so please, help! :)

#4
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Try googling around for information on wait and notify in java. There are tons of resources on this subject.

#5
dusch

dusch

    Newbie

  • Members
  • Pip
  • 4 posts
I tried, but I didn't find what I am looking for..
I wrote this peace of code, but I know it's not good, it should be process for
that is the suspend() called get to sleep, not process that is calling suspend(), and I do not know how to do it right.

import java.util.concurrent.*;

public class Domaci1 {
private boolean bad=false;

public synchronized void methodSuspend() {
while(bad=true) {
try {
wait();
} catch(InterruptedException e) {

}
}
}
public synchronized void methodResume() {
if(bad=false) {
notify();
}
}

}

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I didn't actually run the code, but this would seem better. As you didn't really use your "bad" boolean a lot, or at least wrong.
You need 2x"=" to check for equality, otherwise you just change the boolean's value.

So something like this would already be a step closer.
import java.util.concurrent.*;

public class Domaci1 {
  private boolean suspend = false;


  public synchronized void methodSuspend() {
    while(suspend) {
      try {
        wait();
      } catch(InterruptedException e) { }
    }
  }


  public synchronized void methodResume() {
    if(suspend) {
      suspend = false;
      notify();
    }
  }
}

But, to actually call wait and notifiy on an Object you need the Object's lock. This is done using the "synchronize" keyword. I am however unsure if you can actually synchronize yourself...

#7
dusch

dusch

    Newbie

  • Members
  • Pip
  • 4 posts
Thank you very much for the solution, and thanks for reminding, I know it's a "==" but I've accidentally made a mistake..




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users