Junior — Middle
Can you tell about the process of implementing threads or multitasking in your previous project?
sobes.tech AI
Answer from AI
Multitasking in Java is usually implemented using threads. In my previous project, I used the Thread class and the Runnable interface to create and manage threads.
Main steps:
- Created a class implementing Runnable, where I described the logic to be executed in a separate thread.
- Created a Thread object, passing the Runnable to it.
- Started the thread using the start() method, which allowed tasks to run in parallel.
For more complex tasks, I used ExecutorService from the java.util.concurrent package, which manages a thread pool and simplifies their usage.
Example:
class MyTask implements Runnable {
public void run() {
System.out.println("Executing task in thread " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.start();
}
}
This approach allows multiple tasks to be executed simultaneously, improving application performance.