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

    1 answer 1

    Manually calling the run method is not very good. It is better to do so that the Consumer is responsible for handling incoming lines.

    ConcurrentLinkedQueue uses a wait-free algorithm and does not block the thread that reaches the element if the queue is empty.

    This is an implementation of the algorithm that has been approved for the use of the non-blocking and concurrent queuing algorithms by Michael M. Michael and Michael L. Scott.

    This queue implementation is usually designed for intensive exchanges between the producer and the data consumer. Also when the number of competing flows is large.

    Since you have only one worker, it will be better to replace ConcurrentLinkedQueue with LinkedBlockingQueue and use the take method. This method will block the worker thread until there is data in the queue.

    • Thank you, I took your advice! - Kirill Stoianov