1

I am working with threads and need to first retrieve an object from a collection and then execute the method in that object. I used the ArrayList.get(0) to retrieve the first element, but now how do I execute the run() method for my Runnable object that I just retrieved?

Here is my code so far:

public class MyThread extends Thread{

//Instance Variables
private List<Runnable> requestQueue;

//Constructor
public MyThread() {
    requestQueue = new LinkedList<Runnable>();
}

//Methods
public void run() {
    while (!requestQueue.isEmpty()) { 
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        requestQueue.get(0);
    }
}

}

4
  • Is there a reason you need to execute each Runnable task in sequences? Commented Nov 7, 2012 at 1:11
  • Might I suggest that something in the java.util.concurrent package such as ExecutorService could provide the functionality you're looking for? Commented Nov 7, 2012 at 1:33
  • instead of using List, you may want to use Queue or BlockingQueue Commented Nov 7, 2012 at 1:34
  • @logan Yes, I'm told that ExecutorService makes life much easier, however, I'm doing this for a homework assignment and they want us to have a better understanding of threading, wait/notify, and synchronization... Commented Nov 7, 2012 at 1:39

1 Answer 1

2

While you queue is not empty you can run:

new Thread(requestQueue.get(0)).start();

BTW: You should be getting a cyclic name conflict indicating that you can't extend Thread. You could rename the class to, say, MyThread.

Also have a look at ExecutorService as a means of abstracting many of the complexities associated with the lower-level abstractions like raw Thread.

Sign up to request clarification or add additional context in comments.

5 Comments

Well, this isn't my main method, but in my main method I plan on creating the new thread. In which case, the new operator would not be necessary here, right?
It's actually called by a different name, but I wanted it to be as general as possible.
Yes, that's fine but would suggest calling your class something other than Thread...
If I were to create a new Thread in myThread then what you stated would be correct, but if I intend on creating the new Thread in another class then my code in myThread would need to be requestQueue.get(0).run();
No. just calling run() does not make it a Thread. You need to wrap your Runnable objects in new Threads for them to be threaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.