Runnable tasks
Description
Runnable represents work with no return value.
Explanation
Pass it to a Thread for a simple demonstration.
Example
Thread worker = new Thread(() -> System.out.println("Working"));← Chapter 10 — Threads, Networking & JDBC
mixed
A thread is an independent path of execution within a program. Multiple threads can keep a user interface responsive or perform independent tasks at the same time.
Concurrency adds complexity because threads may access shared state in an unpredictable order. Start by using high-level tools such as Runnable and ExecutorService.
Runnable represents work with no return value.
Pass it to a Thread for a simple demonstration.
Thread worker = new Thread(() -> System.out.println("Working"));Several threads can reach the same object.
Synchronization or thread-safe structures protect coordinated updates.
synchronized (lock) { score++; }Calling run executes code on the current thread; calling start creates a new thread that later calls run. Avoid using Thread.sleep as a coordination strategy in production code.
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> System.out.println("Rohan is processing scores"));
worker.start();
worker.join();
System.out.println("Done");
}
}