Java
Beginner
1 min read
Thread and Runnable
Example
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadDemo {
// Runnable task (preferred over extending Thread)
static class CounterTask implements Runnable {
private final String name;
private final int count;
CounterTask(String name, int count) {
this.name = name;
this.count = count;
}
@Override
public void run() {
for (int i = 1; i <= count; i++) {
System.out.printf("[%s] step %d%n", name, i);
try {
Thread.sleep(50); // simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore flag
System.out.println(name + " interrupted");
return;
}
}
}
}
// Thread-safe counter using AtomicInteger
static AtomicInteger sharedCounter = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new CounterTask("Alpha", 3));
Thread t2 = new Thread(new CounterTask("Beta", 3));
t1.start();
t2.start();
t1.join(); // wait for t1 to finish
t2.join(); // wait for t2 to finish
System.out.println("Both threads finished");
// Concurrent increments with AtomicInteger
Runnable incrementer = () -> {
for (int i = 0; i < 1000; i++) sharedCounter.incrementAndGet();
};
Thread[] workers = new Thread[5];
for (int i = 0; i < 5; i++) { workers[i] = new Thread(incrementer); workers[i].start(); }
for (Thread w : workers) w.join();
System.out.println("Shared counter (expected 5000): " + sharedCounter.get());
}
}