Creating and Running Threads
Multithreading in Java allows concurrent execution of two or more threads. Threads are independent units of execution that share the same resources and can run in parallel.
Creating Threads by Extending Thread
Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // Start the thread
}
}
Creating Threads by Implementing Runnable
Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running...");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // Start the thread
}
}
Threads can be created by extending the Thread
class or by implementing the Runnable
interface. Both methods involve defining a run()
method where the thread's logic resides.
Last updated