Java Concurrency Tutorial
Selected Reading
- Concurrency - Discussion
- Concurrency - Useful Resources
- Concurrency - Quick Guide
- ConcurrentNavigableMap
- Concurrency - ConcurrentMap
- Concurrency - BlockingQueue
- Concurrency - Fork-Join framework
- Concurrency - Futures and Callables
- ScheduledThreadPoolExecutor
- Concurrency - ThreadPoolExecutor
- newSingleThreadExecutor
- newScheduledThreadPool
- Concurrency - newCachedThreadPool
- Concurrency - newFixedThreadPool
- ScheduledExecutorService
- Concurrency - ExecutorService
- Concurrency - Executor
- Concurrency - AtomicReferenceArray
- Concurrency - AtomicLongArray
- Concurrency - AtomicIntegerArray
- Concurrency - AtomicReference
- Concurrency - AtomicBoolean
- Concurrency - AtomicLong
- Concurrency - AtomicInteger
- Concurrency - Condition
- Concurrency - ReadWriteLock
- Concurrency - Lock
- Concurrency - ThreadLocalRandom
- Concurrency - ThreadLocal
- Concurrency - Deadlock
- Concurrency - Synchronization
- Interthread Communication
- Concurrency - Major Operations
- Concurrency - Environment Setup
- Concurrency - Overview
- Concurrency - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Concurrency - Synchronization
Java Concurrency - Synchronization
Multithreading Example with Synchronization
Here is the same example which prints counter value in sequence and every time we run it, it produces the same result.
Example
class PrintDemo { pubpc void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; ThreadDemo(String name, PrintDemo pd) { threadName = name; PD = pd; } pubpc void run() { synchronized(PD) { PD.printCount(); } System.out.println("Thread " + threadName + " exiting."); } pubpc void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } pubpc class TestThread { pubpc static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD); ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch (Exception e) { System.out.println("Interrupted"); } } }
This produces the same result every time you run this program −
Output
Starting Thread - 1 Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 1 exiting. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting.Advertisements