Senior
What was Worker? How does it work?
sobes.tech AI
Answer from AI
In the context of Java, the term "Worker" often refers to a separate thread or task that performs some work asynchronously or in the background. Usually, a Worker is an object implementing the Runnable or Callable interface, which is started in a separate thread or through a thread pool (ExecutorService).
Working principle:
- The Worker receives a task to perform.
- It is launched in a separate thread.
- It performs its work (e.g., data processing, calculations).
- Upon completion, it can return a result or signal completion.
Example of a simple Worker in Java:
public class Worker implements Runnable {
private String taskName;
public Worker(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("Executing task: " + taskName);
// Work logic here
}
}
// Usage:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new Worker("Task 1"));
executor.shutdown();
Thus, a Worker is a unit of work executed in a separate thread, enabling parallel task processing.