Junior — Middle
Kuidas saab Java's andmevoogude loomist realiseerida ja millised on nende erinevused?
sobes.tech AI
Vastus AI-lt
In Java, creating data streams (streams) can be implemented in several ways:
-
Inheritance from the Thread class
- Create a class that extends
Threadand overrides therun()method. - Start the stream by calling
start().
- Create a class that extends
-
Implementation of the Runnable interface
- Create a class that implements
Runnablewith therun()method. - Pass the object to the
Threadconstructor and start it.
- Create a class that implements
-
Using ExecutorService
- Allows managing a thread pool.
- Useful for scalable applications.
-
Using Callable and Future
- Allows obtaining a result from the thread.
Differences:
- Inheriting from
Threadlimits inheritance, as Java does not support multiple inheritance. - Runnable is more flexible, allowing composition.
- ExecutorService simplifies thread management and their lifecycle.
Example with Runnable:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}