</>
Skip to content
Java lessons (43/47)

Java — Threads

Creating threads

// Thread class
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}

// Runnable
Runnable task = () -> System.out.println("Task running");

new MyThread().start();
new Thread(task).start();

Thread methods

Thread t = new Thread(() -> {
    System.out.println("Running: " + Thread.currentThread().getName());
});

t.setName("Worker");
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join(); // Wait for completion

Synchronized

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

ExecutorService

import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 0; i < 5; i++) {
    executor.submit(() -> {
        System.out.println(Thread.currentThread().getName());
    });
}

executor.shutdown();

Callable and Future

import java.util.concurrent.*;

Callable<Integer> task = () -> {
    Thread.sleep(1000);
    return 42;
};

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);

System.out.println(future.get()); // 42
executor.shutdown();

ConcurrentHashMap

import java.util.concurrent.*;

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("counter", 0);

// Atomic operations
map.compute("counter", (k, v) -> v + 1);

Mini Practice

Write Java code that:

  1. Creates a thread with Runnable
  2. Uses synchronized for thread safety
  3. Uses ExecutorService for parallel tasks
  4. Uses Callable and Future

Up Next

Congratulations! You've completed the Java fundamentals. Continue exploring advanced topics like annotations, reflection, and design patterns.

Related Topics

Frequently Asked Questions about Threads

What is Threads in Java?

Threads is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Threads?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Threads.

Why is Threads important in Java?

Threads is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.