Sobes.tech
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:

  1. Inheritance from the Thread class

    • Create a class that extends Thread and overrides the run() method.
    • Start the stream by calling start().
  2. Implementation of the Runnable interface

    • Create a class that implements Runnable with the run() method.
    • Pass the object to the Thread constructor and start it.
  3. Using ExecutorService

    • Allows managing a thread pool.
    • Useful for scalable applications.
  4. 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();
    }
}