Java Multithreading Concepts
1. Runnable Interface
In Java, the Runnable interface is used to define a task that can run on a thread.
To use it, implement the run() method. Example:
class MyTask implements Runnable {
public void run() {
[Link]("Task running using Runnable");
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
[Link]();
2. Extending Thread Class
Another method of creating threads is extending the Thread class and overriding its run()
method.
Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread running using Thread class");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
3. Synchronization in Threads
Synchronization ensures that only one thread accesses shared resources at a time.
Example of synchronized method:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
public int getCount() { return count; }
4. Executor Framework
Executor Framework simplifies thread management.
Example using ExecutorService:
import [Link].*;
class MyTask implements Runnable {
public void run() {
[Link]("Task executed by executor");
public class Main {
public static void main(String[] args) {
ExecutorService executor = [Link](2);
[Link](new MyTask());
[Link]();