Dev_anon101 Dev_anon101 - 4 months ago 8
Android Question

How to run a task on a specific thread which is active?

Is there a way I can do a similar task like the android OS or java AWT thread where a task is run on a particular thread regardless of which thread of which thread the method was called from e.g. repaint().

private Thread thread;
public void startThread(){ //method which start's my thread
thread = new Thread(new Runnable(){
doSomething();
});
thread.start()
}

public void submitTask(Runnable runnable){
//run the runnable task on the thread "thread"
}


How can I achieve something like this, on a situation where I have more then one active thread

Answer

How I've dealt with this scenario before is to create a work queue and a thread which processes tasks that get added to it. So any thread can add a work item to the queue and the same thread will process it regardless of what thread added the work item.

 public class MyClass {

    private LinkedBlockingQueue<MyTask> myTaskProcessingQueue;

    public MyClass() {
        myTaskProcessingQueue = new LinkedBlockingQueue<MyTask>();
        new MyTaskWorker().start();
    }

    public void processTask(MyTask myTask) {
        myTaskProcessingQueue.put(myTask);
    }

    private class MyTaskWorker extends Thread {

        @Override
        public void run() {
            while (true) {
                try {
                    processMyTask(myTaskProcessingQueue.take());
                } catch (InterruptedException ie) {
                    // handle it
                }
            }
        }

        private void processMyTask(MyTask myTask) {
            // do work
        }
    }
}
Comments