Junior — Middle
What methods can be used to implement data stream creation in Java?
sobes.tech AI
Answer from AI
In Java, creating data streams (execution threads) can be implemented in several ways:
- Inheriting from the
Threadclass Create a class that inherits fromThreadand override therun()method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
MyThread t = new MyThread();
t.start();
- Implementing the
Runnableinterface Create a class that implementsRunnableand pass it to theThreadconstructor.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread via Runnable");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- Using lambda expressions (since Java 8)
Thread t = new Thread(() -> System.out.println("Thread via lambda"));
t.start();
- Using
ExecutorServiceand thread pools
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task in thread pool"));
executor.shutdown();
These methods allow creating and managing threads for parallel task execution.