Runnables and Threads


R. Clayton (rclayton@monmouth.edu)
(no date)


I'm trying to do something along the lines of this:

  ConsumerRunnable me = (ConsumerRunnable) Thread.currentThread();

but the code isn't compiling:

  Store.java:113: inconvertible types
  found : java.lang.Thread
  required: ConsumerRunnable

What's wrong?

  Thread implements Runnable, so you can up-cast a Thread instance to a
  Runnable instance:

    Runnable r = (Runnable) (new Thread(new CustomerRunnable()))

  You can also up-cast an instance a Thread descendent into a Runnable
  instance, because the Thread descendent sill implements Runnable:

    Runnable r = (Runnable) (new CustomerThread(new CustomerRunnable()))

  However, you can't cast a Thread instance into an instance of a Runnable
  descendent because Thread is not directly related to the Runnable descendent:

                Runnable
                  / \
      implements / \ extends
                / \
          Thread CustomerRunnable
              /
     extends /
            /
     ConsumerThread

  Essentially what you want is a Thread that implements CustomerRunnable; right
  off hand, I don't see how to do that easily.

I need to cast the Thread type down, a reference to Thread is no good to me
because then I can't access my member functions. Is there a way around this
problem?

  I'm not sure where these member functions are; I'm assuming they're in
  ConsumerRunnable. If that's the case, you're stuck because the Thread
  interface doesn't let you get at the associated Runnable instance.

  Right off hand, I can think of two ways around this problem. First, keep a
  map between threads and their runnables so that t2r[t] is the runnable
  associated with thread instance t. That's a simple but clumsy solution
  because you have to maintain the map yourself and then drag it around to all
  the code that needs to use it.

  The second solution is to extend Thread to add a getRunnable method:

    class OpenRunnableThread
    extends Thread {

      private final Runnable r;

      Runnable
      getRunnable() {
        return r;
        }

      OpenRunnableThread(Runnable r) {
        super(r);
        this.r = r;
        }
      }

  getRunnable() returns a Runnable instance, but you can down-cast it to an
  instance of the implemented Runnable:

    ConsumerRunnable cr = (ConsumerRunnable)
      (new OpenRunnableThread(new ConsumerRunnable())).getRunnable();



This archive was generated by hypermail 2.0b3 on Tue Aug 12 2003 - 09:30:05 EDT