Java.Multithreading.How can a thread be created?

🔨 1. Extending Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Hello from thread!");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // Don't call run() directly!
    }
}

✅ Easy to use
❌ Can’t extend another class (Java has single inheritance)

🔧 2. Implementing Runnable Interface

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Running from a Runnable!");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}

✅ More flexible than extending Thread
✅ Preferred when task logic is separate from thread mechanics

⚡ 3. Using Lambda (Recommended for Simple Tasks)

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("Lambda thread!");
        });
        t.start();
    }
}

✅ Very concise
✅ Modern and clean for short tasks

🛠 4. Using ExecutorService (Better Thread Management)

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        executor.submit(() -> {
            System.out.println("Task executed by thread pool");
        });

        executor.shutdown();
    }
}

✅ Better for scaling and managing many threads
✅ Avoids manual thread creation
✅ Use Future to get result if needed

🌱 5. Using Virtual Threads (Java 21+, Project Loom)

public class Main {
    public static void main(String[] args) {
        Thread.startVirtualThread(() -> {
            System.out.println("Hello from a virtual thread!");
        });
    }
}

✅ Ultra-lightweight
✅ Can spawn millions of threads
✅ Great for concurrent IO without blocking

Requires Java 21+ with virtual threads enabled.

🧠 Summary Table

MethodThread ControlReusabilityModern?Notes
extends ThreadManual❌ No❌ OldSubclassing, inflexible
implements RunnableManual✅ Yes✅ OKClean separation of logic
LambdaManual✅ Yes✅✅✅Best for short, inline tasks
ExecutorServiceManaged✅✅✅✅✅Scalable thread pooling
Virtual ThreadsManaged✅✅✅✅✅✅✅Lightweight & ideal for IO-heavy
This entry was posted in Без рубрики. Bookmark the permalink.