How to change a thread's Runnable target during runtime

Patrick :

I want to build my own ExecutorService in Java which is able to 'submit(Callable task)' a given task. I intended to use a thread pool comprising several 'Threads(Runnable target)'. The idea is to create a fixed number of threads which dequeue FutureTask objects from a list that has been filled by the 'submit' method. The FutureTask objects have been created within the submit method as well. My problem is that I can only hand over a Runnable object(here: FutureTask) to a thread when the thread is created (via constructor), but obviously FutureTasks need to be assigned to a thread dynamically (when the item is removed from the list). Is there any way to do this?

// content of submit, parameter: myTask
FutureTask<V> newFutureTask = new FutureTask<V>(myTask);
taskQueue = new BlockingQueue<FutureTask<V>>();
try {
    taskQueue.put(newFutureTask);
} catch (InterruptedException ex) { }
return newFutureTask;

// remove item from list and hand it over to thread
// method within MyThread extends Thread (thread pool) class
void exec() {
    FutureTask<V> task;
    try {
        task = taskQueue.take();
        // TODO: run task somehow????
        } catch(InterruptedException ex) { }
}
GhostCat salutes Monica C. :

See a bit of pseudo code:

while (true) {
   task = fetch task
   If no task: wait/yield
   Else: execute task 
}

In other words: you simply have to implement a run() method that loops and executes the run method of any Runnable (or whatever is passed to it). If no work is available, that methods sleeps, or waits to be notified.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156479&siteId=1