Junior — Middle
What methods can be used to create data streams in Java, and what are their differences?
sobes.tech AI
Answer from AI
In Java, creating data streams can be implemented in several ways:
-
Inheriting from the Thread class
- Create a class that extends
Threadand override therun()method. - Start the thread by calling
start().
- Create a class that extends
-
Implementing the Runnable interface
- Create a class that implements
Runnablewith arun()method. - Pass the object to the
Threadconstructor and start it.
- Create a class that implements
-
Using ExecutorService
- Allows managing a thread pool.
- Convenient for scalable applications.
-
Using Callable and Future
- Allows obtaining a result from the thread.
Differences:
- Inheriting from Thread limits 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();
}
}