Results 1 to 3 of 3
  1. #1
    Mkaveli is offline Member
    Join Date
    Mar 2010
    Posts
    3
    Rep Power
    0

    Default Need help with wait() and notify()

    public class ThreadPool {

    static ExecutorService pool;
    static LinkedList<Runnable> list = new LinkedList<Runnable>();
    static ThreadWorker threadWorker = new ThreadWorker();
    static Thread worker = new Thread(threadWorker);

    ThreadPool(){
    pool = Executors.newSingleThreadExecutor();
    pool.execute(worker);
    }

    ThreadPool(int size){
    pool = Executors.newFixedThreadPool(size);
    pool.execute(worker);
    }

    synchronized void add(Runnable task){
    list.add(task);
    notifyAll();
    }

    void stopPool(){
    pool.shutdown();
    }
    }

    class ThreadWorker implements Runnable{

    public synchronized void run(){
    while(true){
    if(ThreadPool.list.size() == 0){
    try {
    System.out.println("Worker is waiting!!");
    this.wait();
    } catch (InterruptedException e) {
    System.out.println(e);
    }
    }
    else{
    ThreadPool.list.poll().run();
    }
    }
    }
    }

    It seems that the notifyAll() doesn't activate de wait() in the ThreadWorker class. I was wondering what i am doing wrong. thank you

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please don't bump your post with a link in two other threads or multipost a question.
    Last edited by Fubarable; 03-28-2010 at 02:33 PM.

  3. #3
    dgaur's Avatar
    dgaur is offline Member
    Join Date
    Mar 2010
    Location
    Noida, india
    Posts
    7
    Rep Power
    0

    Post Wait and Notify

    The wait and notify methods works on the same object only.

    In your case you are calling these two methods on different object, which is of no use.

    Try making a shared Object somewhere in your code and then call these two methods on that object only. It should work.

Similar Threads

  1. Wait() notify() implementation
    By georges in forum Advanced Java
    Replies: 4
    Last Post: 02-05-2010, 01:33 AM
  2. wait() and notify() trouble with UI
    By Atriamax in forum Threads and Synchronization
    Replies: 2
    Last Post: 12-09-2009, 02:51 AM
  3. wait() and notify() problems
    By greyradio in forum Threads and Synchronization
    Replies: 1
    Last Post: 08-03-2009, 03:36 AM
  4. What is the execution path of wait() and notify() ?
    By AegisCruiser in forum Threads and Synchronization
    Replies: 1
    Last Post: 04-23-2008, 06:16 PM

Posting Permissions

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