Concurrent Thread Increment: Java Program to Create and Start Multiple Threads
Write a Java program to create and start multiple threads that increment a shared counter variable concurrently.
Sample Solution:
Java Code:
Sample Output:
Final count: 60000
Explanation:
In the above exercise -
- First, we define a "Counter" class that represents a shared counter variable. It has a synchronized increment() method that increments the counter variable by one.
- Next we define an "IncrementThread" class that extends Thread. Each IncrementThread instance increments the shared counter by a specified number of increments.
- In the Main class, we create a 'Counter' object, specify the number of threads and increments per thread, and create an array of 'IncrementThread' objects. We then iterate over the array, creating and starting each thread.
- After starting all the threads, we use the join() method to wait for each thread to finish before proceeding. After all threads have finished, we print the shared counter's final count.
Flowchart:



For more Practice: Solve these Related Problems:
- Write a Java program to create multiple threads that increment a shared counter using AtomicInteger for thread-safe operations.
- Write a Java program to create multiple threads that increment a shared counter using synchronized blocks and then print the final value.
- Write a Java program to implement multiple threads that increment a shared counter and use a CountDownLatch to wait for all threads to finish.
- Write a Java program to create multiple threads that increment a shared counter and use a CyclicBarrier to synchronize their completion before printing the result.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java Multithreading Exercises Home.
Next: Java Program with wait() and notify() for Thread Synchronization.
What is the difficulty level of this exercise?
Based on 544 votes, average difficulty level of this exercise is Hard
.
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics