In an android app that i am developing, I need to make an extra thread to handle some repetitive tasks. I only need one thread and the task is very simple but frequent, intermittent, and should be in order
I figured out Executors.newSingleThreadExecutor is a good way for these kinds of situations. However, I really don't get the benefit of using this over creating a new thread.
Instead of using Executors.newSingleThreadExecutor and using submit() function to queue tasks, is it bad to just make a dedicated thread? I will make it go through a queue of tasks and when the queue is empty it will wait() and when ever the main thread sends a new task it it will notify() the worker thread. Is this bad practice?
// loop for worker thread
public class WorkerThrd extends Thread {
public void run() {
while(true){
while (!queue.empty()) {
queue.getTask().doSth();
}
synchronized(this){
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
// from main thread
private WorkerThread wthread;
public void initiation(){
wthread = new WorkerThread();
wthread.start();
}
public void postSth(){
wthread.queue.post(new task()); // a thread safety queue
synchronized(wthread){
if(wthread.getState() == Thread.State.WAITING) {
wthread.notify();
}
}
}
P.S. though I assumed the queue is thread safety, should I need a synchronized block whenever I call wait() or notify() ?? even when only one thread will call wait() and one other thread will call notify() ?