├── .gitignore ├── README.md ├── java-callable-and-future-examples ├── Readme.md └── src │ ├── FutureAndCallableExample.java │ ├── FutureCancelExample.java │ ├── FutureIsDoneExample.java │ ├── InvokeAllExample.java │ └── InvokeAnyExample.java ├── java-concurrency-issues-and-synchronization ├── Readme.md └── src │ ├── MemoryConsistencyErrorExample.java │ ├── RaceConditionExample.java │ ├── SynchronizedBlockExample.java │ ├── SynchronizedMethodExample.java │ └── VolatileKeywordExample.java ├── java-executors-and-thread-pool ├── Readme.md └── src │ ├── ExecutorsExample.java │ ├── ScheduledExecutorsExample.java │ └── ScheduledExecutorsPeriodicExample.java ├── java-lock-objects-and-atomic-variables ├── Readme.md └── src │ ├── AtomicIntegerExample.java │ ├── ReadWriteLockExample.java │ ├── ReentrantLockExample.java │ └── ReentrantLockMethodsExample.java └── java-thread-and-runnable-examples ├── Readme.md └── src ├── RunnableExample.java ├── RunnableExampleAnonymousClass.java ├── RunnableExampleLambdaExpression.java ├── ThreadExample.java ├── ThreadJoinExample.java └── ThreadSleepExample.java /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | out 4 | *.iml 5 | *.class 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Concurrency/Multithreading Examples 2 | 3 | ## Relevant Tutorials 4 | 5 | 1. [Java Concurrency / Multithreading Basics](https://www.callicoder.com/java-concurrency-multithreading-basics/) 6 | 7 | 2. [Java Thread and Runnable Tutorial](https://www.callicoder.com/java-multithreading-thread-and-runnable-tutorial/) 8 | 9 | 3. [Java Executors and Thread Pool Tutorial](https://www.callicoder.com/java-executor-service-and-thread-pool-tutorial/) 10 | 11 | 4. [Java Callable and Future Tutorial](https://www.callicoder.com/java-callable-and-future-tutorial/) 12 | 13 | 5. [Java Concurrency issues and Synchronization](https://www.callicoder.com/java-concurrency-issues-and-thread-synchronization/) 14 | 15 | 6. [Java Locks and Atomic Variables](https://www.callicoder.com/java-locks-and-atomic-variables-tutorial/) -------------------------------------------------------------------------------- /java-callable-and-future-examples/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/java-concurrency-examples/cd9f84f9b3237be51fe436e2614b5db11291fe0b/java-callable-and-future-examples/Readme.md -------------------------------------------------------------------------------- /java-callable-and-future-examples/src/FutureAndCallableExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.*; 2 | 3 | /** 4 | * Created by rajeevkumarsingh on 11/05/17. 5 | */ 6 | public class FutureAndCallableExample { 7 | public static void main(String[] args) throws InterruptedException, ExecutionException { 8 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 9 | 10 | Callable callable = () -> { 11 | // Perform some computation 12 | System.out.println("Entered Callable"); 13 | Thread.sleep(2000); 14 | return "Hello from Callable"; 15 | }; 16 | 17 | System.out.println("Submitting Callable"); 18 | Future future = executorService.submit(callable); 19 | // This line executes immediately 20 | System.out.println("Do something else while callable is getting executed"); 21 | 22 | System.out.println("Retrieve the result of the future"); 23 | // Future.get() blocks until the result is available 24 | String result = future.get(); 25 | System.out.println(result); 26 | 27 | executorService.shutdown(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java-callable-and-future-examples/src/FutureCancelExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.*; 2 | 3 | /** 4 | * Created by rajeevkumarsingh on 10/05/17. 5 | */ 6 | public class FutureCancelExample { 7 | public static void main(String[] args) throws InterruptedException, ExecutionException { 8 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 9 | 10 | Callable callable = () -> { 11 | // Perform some computation 12 | Thread.sleep(2000); 13 | return "Hello from Callable"; 14 | }; 15 | 16 | long startTime = System.nanoTime(); 17 | Future future = executorService.submit(callable); 18 | 19 | while(!future.isDone()) { 20 | System.out.println("Task is still not done..."); 21 | Thread.sleep(200); 22 | double elapsedTimeInSec = (System.nanoTime() - startTime) / 1000000000.0; 23 | 24 | if (elapsedTimeInSec > 1) { 25 | // cancel future if the elapsed time is more than one second 26 | future.cancel(true); 27 | } 28 | } 29 | 30 | // Check if future is cancelled before retrieving the result 31 | if(!future.isCancelled()) { 32 | System.out.println("Task completed! Retrieving the result"); 33 | // Future.get() blocks until the result is available 34 | String result = future.get(); 35 | System.out.println(result); 36 | } else { 37 | System.out.println("Task was cancelled"); 38 | } 39 | 40 | executorService.shutdown(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /java-callable-and-future-examples/src/FutureIsDoneExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.*; 2 | 3 | /** 4 | * Created by rajeevkumarsingh on 11/05/17. 5 | */ 6 | public class FutureIsDoneExample { 7 | public static void main(String[] args) throws InterruptedException, ExecutionException { 8 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 9 | 10 | Future future = executorService.submit(() -> { 11 | Thread.sleep(2000); 12 | return "Hello from Callable"; 13 | }); 14 | 15 | while(!future.isDone()) { 16 | System.out.println("Task is still not done..."); 17 | Thread.sleep(200); 18 | } 19 | 20 | System.out.println("Task completed! Retrieving the result"); 21 | String result = future.get(); 22 | System.out.println(result); 23 | 24 | executorService.shutdown(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /java-callable-and-future-examples/src/InvokeAllExample.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.concurrent.*; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 10/05/17. 7 | */ 8 | public class InvokeAllExample { 9 | public static void main(String[] args) throws InterruptedException, ExecutionException { 10 | ExecutorService executorService = Executors.newFixedThreadPool(5); 11 | 12 | Callable task1 = () -> { 13 | Thread.sleep(2000); 14 | return "Result of Task1"; 15 | }; 16 | 17 | Callable task2 = () -> { 18 | Thread.sleep(1000); 19 | return "Result of Task2"; 20 | }; 21 | 22 | Callable task3 = () -> { 23 | Thread.sleep(5000); 24 | return "Result of Task3"; 25 | }; 26 | 27 | List> taskList = Arrays.asList(task1, task2, task3); 28 | 29 | List> futures = executorService.invokeAll(taskList); 30 | 31 | for(Future future: futures) { 32 | // The result is printed only after all the futures are complete. (i.e. after 5 seconds) 33 | System.out.println(future.get()); 34 | } 35 | 36 | executorService.shutdown(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java-callable-and-future-examples/src/InvokeAnyExample.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.concurrent.*; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 10/05/17. 7 | */ 8 | public class InvokeAnyExample { 9 | public static void main(String[] args) throws InterruptedException, ExecutionException { 10 | ExecutorService executorService = Executors.newFixedThreadPool(5); 11 | 12 | Callable task1 = () -> { 13 | Thread.sleep(2000); 14 | return "Result of Task1"; 15 | }; 16 | 17 | Callable task2 = () -> { 18 | Thread.sleep(1000); 19 | return "Result of Task2"; 20 | }; 21 | 22 | Callable task3 = () -> { 23 | Thread.sleep(5000); 24 | return "Result of Task3"; 25 | }; 26 | 27 | // Returns the result of the fastest callable. (task2 in this case) 28 | String result = executorService.invokeAny(Arrays.asList(task1, task2, task3)); 29 | 30 | System.out.println(result); 31 | 32 | executorService.shutdown(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/java-concurrency-examples/cd9f84f9b3237be51fe436e2614b5db11291fe0b/java-concurrency-issues-and-synchronization/Readme.md -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/src/MemoryConsistencyErrorExample.java: -------------------------------------------------------------------------------- 1 | public class MemoryConsistencyErrorExample { 2 | private static boolean sayHello = false; 3 | 4 | public static void main(String[] args) throws InterruptedException { 5 | 6 | Thread thread = new Thread(() -> { 7 | while(!sayHello) { 8 | 9 | } 10 | 11 | System.out.println("Hello World!"); 12 | 13 | while(sayHello) { 14 | 15 | } 16 | 17 | System.out.println("Good Bye!"); 18 | }); 19 | 20 | thread.start(); 21 | 22 | Thread.sleep(1000); 23 | System.out.println("Say Hello.."); 24 | sayHello = true; 25 | 26 | Thread.sleep(1000); 27 | System.out.println("Say Bye.."); 28 | sayHello = false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/src/RaceConditionExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 11/05/17. 7 | */ 8 | class Counter { 9 | private int count = 0; 10 | 11 | public void increment() { 12 | count = count + 1; 13 | } 14 | 15 | public int getCount() { 16 | return count; 17 | } 18 | } 19 | 20 | public class RaceConditionExample { 21 | 22 | public static void main(String[] args) throws InterruptedException { 23 | ExecutorService executorService = Executors.newFixedThreadPool(10); 24 | 25 | Counter counter = new Counter(); 26 | 27 | for(int i = 0; i < 1000; i++) { 28 | executorService.submit(() -> counter.increment()); 29 | } 30 | 31 | executorService.shutdown(); 32 | executorService.awaitTermination(60, TimeUnit.SECONDS); 33 | 34 | System.out.println("Final count is : " + counter.getCount()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/src/SynchronizedBlockExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 11/05/17. 7 | */ 8 | class FineGrainedSynchronizedCounter { 9 | private int count = 0; 10 | 11 | public void increment() { 12 | // Synchronized Block 13 | synchronized (this) { 14 | count = count + 1; 15 | } 16 | } 17 | 18 | public int getCount() { 19 | return count; 20 | } 21 | } 22 | 23 | public class SynchronizedBlockExample { 24 | public static void main(String[] args) throws InterruptedException { 25 | ExecutorService executorService = Executors.newFixedThreadPool(10); 26 | FineGrainedSynchronizedCounter counter = new FineGrainedSynchronizedCounter(); 27 | 28 | for(int i = 0; i < 1000; i++) { 29 | executorService.submit(() -> counter.increment()); 30 | } 31 | 32 | executorService.shutdown(); 33 | executorService.awaitTermination(60, TimeUnit.SECONDS); 34 | 35 | System.out.println("Final count is " + counter.getCount()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/src/SynchronizedMethodExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 11/05/17. 7 | */ 8 | class SynchronizedCounter { 9 | private int count = 0; 10 | 11 | // Synchronized Method 12 | public synchronized void increment() { 13 | System.out.println(Thread.currentThread().getName()); 14 | count = count + 1; 15 | } 16 | 17 | public int getCount() { 18 | return count; 19 | } 20 | } 21 | 22 | public class SynchronizedMethodExample { 23 | public static void main(String[] args) throws InterruptedException { 24 | ExecutorService executorService = Executors.newFixedThreadPool(10); 25 | 26 | SynchronizedCounter synchronizedCounter = new SynchronizedCounter(); 27 | 28 | for(int i = 0; i < 1000; i++) { 29 | executorService.submit(() -> synchronizedCounter.increment()); 30 | } 31 | 32 | executorService.shutdown(); 33 | executorService.awaitTermination(60, TimeUnit.SECONDS); 34 | 35 | System.out.println("Final count is : " + synchronizedCounter.getCount()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java-concurrency-issues-and-synchronization/src/VolatileKeywordExample.java: -------------------------------------------------------------------------------- 1 | public class VolatileKeywordExample { 2 | private static volatile boolean sayHello = false; 3 | 4 | public static void main(String[] args) throws InterruptedException { 5 | 6 | Thread thread = new Thread(() -> { 7 | while(!sayHello) { 8 | 9 | } 10 | 11 | System.out.println("Hello World!"); 12 | 13 | while(sayHello) { 14 | 15 | } 16 | 17 | System.out.println("Good Bye!"); 18 | }); 19 | 20 | thread.start(); 21 | 22 | Thread.sleep(1000); 23 | System.out.println("Say Hello.."); 24 | sayHello = true; 25 | 26 | Thread.sleep(1000); 27 | System.out.println("Say Bye.."); 28 | sayHello = false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java-executors-and-thread-pool/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/java-concurrency-examples/cd9f84f9b3237be51fe436e2614b5db11291fe0b/java-executors-and-thread-pool/Readme.md -------------------------------------------------------------------------------- /java-executors-and-thread-pool/src/ExecutorsExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 09/05/17. 7 | */ 8 | public class ExecutorsExample { 9 | public static void main(String[] args) { 10 | System.out.println("Inside : " + Thread.currentThread().getName()); 11 | 12 | System.out.println("Creating Executor Service with a thread pool of Size 2"); 13 | ExecutorService executorService = Executors.newFixedThreadPool(2); 14 | 15 | Runnable task1 = () -> { 16 | System.out.println("Executing Task1 inside : " + Thread.currentThread().getName()); 17 | try { 18 | TimeUnit.SECONDS.sleep(2); 19 | } catch (InterruptedException ex) { 20 | throw new IllegalStateException(ex); 21 | } 22 | }; 23 | 24 | Runnable task2 = () -> { 25 | System.out.println("Executing Task2 inside : " + Thread.currentThread().getName()); 26 | try { 27 | TimeUnit.SECONDS.sleep(4); 28 | } catch (InterruptedException ex) { 29 | throw new IllegalStateException(ex); 30 | } 31 | }; 32 | 33 | Runnable task3 = () -> { 34 | System.out.println("Executing Task3 inside : " + Thread.currentThread().getName()); 35 | try { 36 | TimeUnit.SECONDS.sleep(3); 37 | } catch (InterruptedException ex) { 38 | throw new IllegalStateException(ex); 39 | } 40 | }; 41 | 42 | 43 | System.out.println("Submitting the tasks for execution..."); 44 | executorService.submit(task1); 45 | executorService.submit(task2); 46 | executorService.submit(task3); 47 | 48 | executorService.shutdown(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java-executors-and-thread-pool/src/ScheduledExecutorsExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.Executors; 2 | import java.util.concurrent.ScheduledExecutorService; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 10/05/17. 7 | */ 8 | public class ScheduledExecutorsExample { 9 | public static void main(String[] args) { 10 | ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); 11 | Runnable task = () -> { 12 | System.out.println("Executing Task At " + System.nanoTime()); 13 | }; 14 | 15 | System.out.println("Submitting task at " + System.nanoTime() + " to be executed after 5 seconds."); 16 | scheduledExecutorService.schedule(task, 5, TimeUnit.SECONDS); 17 | 18 | scheduledExecutorService.shutdown(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java-executors-and-thread-pool/src/ScheduledExecutorsPeriodicExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.Executors; 2 | import java.util.concurrent.ScheduledExecutorService; 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Created by rajeevkumarsingh on 10/05/17. 7 | */ 8 | public class ScheduledExecutorsPeriodicExample { 9 | public static void main(String[] args) { 10 | ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); 11 | 12 | Runnable task = () -> { 13 | System.out.println("Executing Task At " + System.nanoTime()); 14 | }; 15 | 16 | System.out.println("scheduling task to be executed every 2 seconds with an initial delay of 0 seconds"); 17 | scheduledExecutorService.scheduleAtFixedRate(task, 0,2, TimeUnit.SECONDS); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java-lock-objects-and-atomic-variables/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/java-concurrency-examples/cd9f84f9b3237be51fe436e2614b5db11291fe0b/java-lock-objects-and-atomic-variables/Readme.md -------------------------------------------------------------------------------- /java-lock-objects-and-atomic-variables/src/AtomicIntegerExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | /** 7 | * Created by rajeevkumarsingh on 24/07/17. 8 | */ 9 | 10 | class AtomicCounter { 11 | private AtomicInteger count = new AtomicInteger(0); 12 | 13 | public int incrementAndGet() { 14 | return count.incrementAndGet(); 15 | } 16 | 17 | public int getCount() { 18 | return count.get(); 19 | } 20 | } 21 | 22 | public class AtomicIntegerExample { 23 | public static void main(String[] args) throws InterruptedException { 24 | ExecutorService executorService = Executors.newFixedThreadPool(2); 25 | 26 | AtomicCounter atomicCounter = new AtomicCounter(); 27 | 28 | for(int i = 0; i < 1000; i++) { 29 | executorService.submit(() -> atomicCounter.incrementAndGet()); 30 | } 31 | 32 | executorService.shutdown(); 33 | executorService.awaitTermination(60, TimeUnit.SECONDS); 34 | 35 | System.out.println("Final Count is : " + atomicCounter.getCount()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java-lock-objects-and-atomic-variables/src/ReadWriteLockExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.locks.ReadWriteLock; 4 | import java.util.concurrent.locks.ReentrantReadWriteLock; 5 | 6 | /** 7 | * Created by rajeevkumarsingh on 11/05/17. 8 | */ 9 | class ReadWriteCounter { 10 | ReadWriteLock lock = new ReentrantReadWriteLock(); 11 | 12 | private int count = 0; 13 | 14 | public int incrementAndGetCount() { 15 | lock.writeLock().lock(); 16 | 17 | try { 18 | count = count + 1; 19 | return count; 20 | } finally { 21 | lock.writeLock().unlock(); 22 | } 23 | } 24 | 25 | public int getCount() { 26 | lock.readLock().lock(); 27 | try { 28 | return count; 29 | } finally { 30 | lock.readLock().unlock(); 31 | } 32 | } 33 | } 34 | 35 | public class ReadWriteLockExample { 36 | 37 | public static void main(String[] args) { 38 | ExecutorService executorService = Executors.newFixedThreadPool(3); 39 | 40 | ReadWriteCounter counter = new ReadWriteCounter(); 41 | 42 | Runnable readTask = () -> { 43 | System.out.println(Thread.currentThread().getName() + 44 | " Read Task : " + counter.getCount()); 45 | }; 46 | 47 | Runnable writeTask = () -> { 48 | System.out.println(Thread.currentThread().getName() + 49 | " Write Task : " + counter.incrementAndGetCount()); 50 | }; 51 | 52 | executorService.submit(readTask); 53 | executorService.submit(readTask); 54 | 55 | executorService.submit(writeTask); 56 | 57 | executorService.submit(readTask); 58 | executorService.submit(readTask); 59 | 60 | executorService.shutdown(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /java-lock-objects-and-atomic-variables/src/ReentrantLockExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | /** 7 | * Created by rajeevkumarsingh on 11/05/17. 8 | */ 9 | class ReentrantLockCounter { 10 | private final ReentrantLock lock = new ReentrantLock(); 11 | 12 | private int count = 0; 13 | 14 | // Thread Safe Increment 15 | public void increment() { 16 | lock.lock(); 17 | try { 18 | count = count + 1; 19 | } finally { 20 | lock.unlock(); 21 | } 22 | } 23 | 24 | public int getCount() { 25 | return count; 26 | } 27 | 28 | } 29 | 30 | 31 | public class ReentrantLockExample { 32 | 33 | public static void main(String[] args) throws InterruptedException { 34 | ExecutorService executorService = Executors.newFixedThreadPool(5); 35 | 36 | ReentrantLockCounter counter = new ReentrantLockCounter(); 37 | 38 | executorService.submit(() -> counter.increment()); 39 | 40 | for(int i = 0; i < 10; i++) { 41 | executorService.submit(() -> counter.increment()); 42 | } 43 | 44 | executorService.shutdown(); 45 | executorService.awaitTermination(60, TimeUnit.SECONDS); 46 | 47 | System.out.println("Final count is : " + counter.getCount()); 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java-lock-objects-and-atomic-variables/src/ReentrantLockMethodsExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ExecutorService; 2 | import java.util.concurrent.Executors; 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | class ReentrantLockMethodsCounter { 7 | private final ReentrantLock lock = new ReentrantLock(); 8 | 9 | private int count = 0; 10 | 11 | public int incrementAndGet() { 12 | // Check if the lock is currently acquired by any thread 13 | System.out.println("IsLocked : " + lock.isLocked()); 14 | 15 | // Check if the lock is acquired by the current thread itself. 16 | System.out.println("IsHeldByCurrentThread : " + lock.isHeldByCurrentThread()); 17 | 18 | // Try to acquire the lock 19 | boolean isAcquired; 20 | try { 21 | isAcquired = lock.tryLock(1, TimeUnit.SECONDS); 22 | System.out.println("Lock Acquired : " + isAcquired + "\n"); 23 | } catch (InterruptedException e) { 24 | throw new IllegalStateException(e); 25 | } 26 | 27 | if(isAcquired) { 28 | try { 29 | Thread.sleep(2000); 30 | count = count + 1; 31 | } catch (InterruptedException e) { 32 | throw new IllegalStateException(e); 33 | } finally { 34 | lock.unlock(); 35 | } 36 | } 37 | return count; 38 | } 39 | } 40 | 41 | public class ReentrantLockMethodsExample { 42 | 43 | public static void main(String[] args) { 44 | ExecutorService executorService = Executors.newFixedThreadPool(2); 45 | 46 | ReentrantLockMethodsCounter lockMethodsCounter = new ReentrantLockMethodsCounter(); 47 | 48 | executorService.submit(() -> { 49 | System.out.println("IncrementCount (First Thread) : " + 50 | lockMethodsCounter.incrementAndGet() + "\n"); 51 | }); 52 | 53 | executorService.submit(() -> { 54 | System.out.println("IncrementCount (Second Thread) : " + 55 | lockMethodsCounter.incrementAndGet() + "\n"); 56 | }); 57 | 58 | executorService.shutdown(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/java-concurrency-examples/cd9f84f9b3237be51fe436e2614b5db11291fe0b/java-thread-and-runnable-examples/Readme.md -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/RunnableExample.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class RunnableExample implements Runnable { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("Inside : " + Thread.currentThread().getName()); 7 | 8 | System.out.println("Creating Runnable..."); 9 | Runnable runnable = new RunnableExample(); 10 | 11 | System.out.println("Creating Thread..."); 12 | Thread thread = new Thread(runnable); 13 | 14 | System.out.println("Starting Thread..."); 15 | thread.start(); 16 | } 17 | 18 | @Override 19 | public void run() { 20 | System.out.println("Inside : " + Thread.currentThread().getName()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/RunnableExampleAnonymousClass.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by rajeevkumarsingh on 08/05/17. 3 | */ 4 | public class RunnableExampleAnonymousClass { 5 | 6 | public static void main(String[] args) { 7 | System.out.println("Inside : " + Thread.currentThread().getName()); 8 | 9 | System.out.println("Creating Runnable..."); 10 | 11 | Runnable runnable = new Runnable() { 12 | @Override 13 | public void run() { 14 | System.out.println("Inside : " + Thread.currentThread().getName()); 15 | } 16 | }; 17 | 18 | System.out.println("Creating Thread..."); 19 | Thread thread = new Thread(runnable); 20 | 21 | System.out.println("Starting Thread..."); 22 | thread.start(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/RunnableExampleLambdaExpression.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by rajeevkumarsingh on 08/05/17. 3 | */ 4 | public class RunnableExampleLambdaExpression { 5 | 6 | public static void main(String[] args) { 7 | System.out.println("Inside : " + Thread.currentThread().getName()); 8 | 9 | System.out.println("Creating Runnable..."); 10 | Runnable runnable = () -> { 11 | System.out.println("Inside : " + Thread.currentThread().getName()); 12 | }; 13 | 14 | System.out.println("Creating Thread..."); 15 | Thread thread = new Thread(runnable); 16 | 17 | System.out.println("Starting Thread..."); 18 | thread.start(); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/ThreadExample.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by rajeevkumarsingh on 08/05/17. 3 | */ 4 | public class ThreadExample extends Thread { 5 | 6 | @Override 7 | public void run() { 8 | System.out.println("Inside : " + Thread.currentThread().getName()); 9 | } 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Inside : " + Thread.currentThread().getName()); 13 | 14 | System.out.println("Creating thread..."); 15 | Thread thread = new ThreadExample(); 16 | 17 | System.out.println("Starting thread..."); 18 | thread.start(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/ThreadJoinExample.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by rajeevkumarsingh on 08/05/17. 3 | */ 4 | 5 | public class ThreadJoinExample { 6 | public static void main(String[] args) { 7 | // Create Thread 1 8 | Thread thread1 = new Thread(() -> { 9 | System.out.println("Entered Thread 1"); 10 | try { 11 | Thread.sleep(2000); 12 | } catch (InterruptedException e) { 13 | throw new IllegalStateException(e); 14 | } 15 | System.out.println("Exiting Thread 1"); 16 | }); 17 | 18 | // Create Thread 2 19 | Thread thread2 = new Thread(() -> { 20 | System.out.println("Entered Thread 2"); 21 | try { 22 | Thread.sleep(4000); 23 | } catch (InterruptedException e) { 24 | throw new IllegalStateException(e); 25 | } 26 | System.out.println("Exiting Thread 2"); 27 | }); 28 | 29 | System.out.println("Starting Thread 1"); 30 | thread1.start(); 31 | 32 | System.out.println("Waiting for Thread 1 to complete"); 33 | try { 34 | thread1.join(1000); 35 | } catch (InterruptedException e) { 36 | throw new IllegalStateException(e); 37 | } 38 | 39 | System.out.println("Waited enough! Starting Thread 2 now"); 40 | thread2.start(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java-thread-and-runnable-examples/src/ThreadSleepExample.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by rajeevkumarsingh on 08/05/17. 3 | */ 4 | public class ThreadSleepExample { 5 | 6 | public static void main(String[] args) { 7 | System.out.println("Inside : " + Thread.currentThread().getName()); 8 | 9 | String[] messages = {"If I can stop one heart from breaking,", 10 | "I shall not live in vain.", 11 | "If I can ease one life the aching,", 12 | "Or cool one pain,", 13 | "Or help one fainting robin", 14 | "Unto his nest again,", 15 | "I shall not live in vain"}; 16 | 17 | Runnable runnable = () -> { 18 | System.out.println("Inside : " + Thread.currentThread().getName()); 19 | 20 | for(String message: messages) { 21 | System.out.println(message); 22 | try { 23 | Thread.sleep(2000); 24 | } catch (InterruptedException e) { 25 | throw new IllegalStateException(e); 26 | } 27 | } 28 | }; 29 | 30 | Thread thread = new Thread(runnable); 31 | 32 | thread.start(); 33 | } 34 | } 35 | --------------------------------------------------------------------------------