neuquen
neuquen

Reputation: 4169

Threads: Retrieving then executing object from ArrayList

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);
    }
}

}

Upvotes: 1

Views: 117

Answers (1)

Reimeus
Reimeus

Reputation: 159754

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.

Upvotes: 2

Related Questions