Junior — Middle
Milliste meetoditega saab Java-s luua ja käivitada andmevoo?
sobes.tech AI
Vastus AI-lt
In Java, there are several main methods to create and start a data stream (execution thread):
- Inheritance from the Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
MyThread thread = new MyThread();
thread.start();
- Implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
- Using lambda expressions (Java 8+)
Thread thread = new Thread(() -> System.out.println("Thread started"));
thread.start();
- Using ExecutorService to manage a thread pool
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Pool thread started"));
executor.shutdown();
Each of these methods allows creating and starting a thread, the choice depends on the task and preferences.