There is a class Worker which contains a queue and when added to the queue a new line has to do some work.
When creating a thread, Runnable is passed to it, which will be launched after the call to the Thread.start() method. After that, new tasks will be added to the Worker in the queue via the .add .add() method, and here the Runnable.run () method will be called again, but manually. Question : I’m wondering if you can do this, in the sense of calling the .run() method manually. PS I set the name Worker in the thread constructor, but then when I check the name of the thread in Runnable that is his name 'main', why does this happen?
public class Worker { private static final String TAG = Worker.class.getSimpleName(); private static final Log log = new Log(TAG); private static Worker instance; private ConcurrentLinkedQueue<String> queryQueue; private WorkerThread workerThread; public static Worker getInstance() { if (instance == null) { instance = new Worker(); } return instance; } private Worker() { source = DBConnectionPool.getInstance().getSource(); queryQueue = new ConcurrentLinkedQueue<>(); workerThread = new WorkerThread(new Consumer(this.queryQueue)); workerThread.start(); } public void add(String s) { this.queryQueue.add(s); workerThread.execute(); } class WorkerThread extends Thread { protected Consumer consumer; public WorkerThread(Consumer target) { this.consumer = target; //set thread name this.setName(this.getClass().getSimpleName()); //name is Worker } public void execute() { this.consumer.run(); } } class Consumer implements Runnable { private ConcurrentLinkedQueue<String> queue; public Consumer(ConcurrentLinkedQueue<String> queue) { this.queue = queue; } @Override public void run() { Thread.currentThread().getName(); // name is: 'main' //do simething } } } Adding items to the queue like this:
Worker.getInstance().add("exampleString");