Member-only story

Building a java application that simulates multithreading

Michael Tong
3 min readJul 18, 2024

--

Photo by Robert Bye on Unsplash

Let’s picture you are waiting for a ride at a theme park. Ideally, everyone would line up and be able to get to the roller coaster right now. In reality there are many people waiting to get onto the roller coaster.

Today, let’s create a program that simulates this situation. Let’s implement the following components:

  • Readers: Each reader is represented by a thread. When a reader tries to occupy a seat in a section, they should print a message indicating whether they found a seat or had to wait.
  • Sections: Each section is represented by a thread. The section should manage the seats and handle readers’ requests to occupy a seat.

We will also have a simulation program that creates 20 threads, simulating a real time scenario with people waiting on the roller coaster, where each person is a thread.

Let’s create Simulation.java:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.Random;

class Section {
private final String name;
private final int capacity;
private int…

--

--

Michael Tong
Michael Tong

Written by Michael Tong

Just a dad spending tons of time building backend services and frontend projects for fun :D

No responses yet