This Java program orchestrates a multithreaded simulation where travelers traverse a wormhole between Earth and Proxima-b. The Traveller class encapsulates individual traveler behavior, utilizing semaphores and atomic variables for synchronization. The P1 class manages the execution of multiple traveler threads, reading input parameters from a specified file. Each traveler undergoes a four-step process to simulate crossing the wormhole, with progress updates and turn toggling. The program outputs detailed journey information, traveler counts, and completion status. Overall, it demonstrates concurrent execution, synchronization, and coordination in a wormhole travel scenario.
Java Multithreading: Wormhole Travel Simulation Project
The provided Java code implements a multithreaded simulation of travelers navigating a wormhole between Earth and Proxima-b. The Traveller class defines individual traveler behavior, incorporating semaphores and atomic variables for synchronization. The P1 class orchestrates the creation and execution of traveler threads, reading input parameters from a file. Each traveler undergoes a staged journey through the wormhole, updating shared counters and toggling turns appropriately. The program outputs detailed progress information for each traveler. This comprehensive solution demonstrates effective multithreading and synchronization techniques in Java, providing a robust foundation for anyone seeking help with their Java assignment in concurrent programming scenarios.
Block 1: Class Definition and Static Fields
class Traveller implements Runnable {
// Static fields shared among all instances of Traveller
private static Semaphore wormholeSemaphore = new Semaphore(1, true);
private static AtomicBoolean earthTurn = new AtomicBoolean(true);
private static AtomicInteger travelersPassed = new AtomicInteger(0);
private static int count = 0;
private static int totalEarth, totalProxima;
// Instance-specific fields
private String id;
private int nTrips;
// Constructor
public Traveller(String id, int nTrips, int totalEarth, int totalProxima) {
this.id = id;
this.nTrips = nTrips;
Traveller.totalEarth = totalEarth;
Traveller.totalProxima = totalProxima;
}
Discussion:
- The Traveller class implements the Runnable interface, indicating that instances of this class can be executed by a thread.
- Static fields are used to share state among all instances of the Traveller class.
- wormholeSemaphore is a semaphore with a single permit, ensuring mutual exclusion when traveling through the wormhole.
- earthTurn is an atomic boolean that determines whose turn it is to travel—Earth's or Proxima-b's.
- travelersPassed keeps track of the number of travelers that have passed through the wormhole.
- count is a counter for the total number of travelers.
- totalEarth and totalProxima store the total number of travelers for Earth and Proxima-b.
Block 2: run Method
@Override
public void run() {
for (int i = 0; i < nTrips; i++) {
try {
System.out.println(id + ": Waiting for wormhole. Travelling towards " + (id.startsWith("E_") ? "Proxima-b" : "Earth"));
while (true) {
if ((id.startsWith("E_") && earthTurn.get()) || (id.startsWith("P_") && !earthTurn.get())) {
if (wormholeSemaphore.tryAcquire(1, TimeUnit.MILLISECONDS)) {
break;
}
}
}
// Wormhole crossing simulation
for (int j = 1; j <= 4; j++) {
Thread.sleep(50); // 50 ms delay
if (j < 4) {
System.out.println(id + ": Crossing wormhole Loading " + j * 25 + "%.");
} else {
// Final step of crossing
System.out.println(id + ": Across the wormhole.");
if (i == nTrips - 1) {
System.out.println(id + " Finished.");
}
// Update counters and toggle turn
synchronized (Traveller.class) {
count++;
System.out.println("COUNT = " + count);
}
travelersPassed.incrementAndGet();
if ((earthTurn.get() && travelersPassed.get() == totalEarth) || (!earthTurn.get() && travelersPassed.get() == totalProxima)) {
travelersPassed.set(0);
earthTurn.set(!earthTurn.get());
}
}
}
wormholeSemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Discussion:
The run method represents the behavior of a traveler when executed by a thread.
- It attempts to acquire the wormhole permit, considering the current turn and type of traveler (Earth or Proxima-b).
- Simulates the journey through the wormhole with a 4-step loading process, introducing delays.
- Updates counters and toggles turns after completing the journey.
- Handles exceptions related to thread interruption.
Main Class (P1)
Block 3: Main Method
public class P1 {
public static void main(String[] args) {
// Input validation
if (args.length < 1) {
System.out.println("Please provide the input filename as an argument.");
return;
}
// Read input parameters from a file
int E = 0, P = 0, N = 0;
try {
Scanner scanner = new Scanner(new File(args[0]));
while (scanner.hasNext()) {
String[] parts = scanner.nextLine().split(", ");
E = Integer.parseInt(parts[0].split("=")[1]);
P = Integer.parseInt(parts[1].split("=")[1]);
N = Integer.parseInt(parts[2].split("=")[1]);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + args[0]);
return;
}
// Create and start traveler threads
Thread[] travellers = new Thread[E + P];
for (int i = 0; i < E; i++) {
travellers[i] = new Thread(new Traveller("E_H" + (i + 1), N, E, P));
}
for (int i = 0; i < P; i++) {
travellers[E + i] = new Thread(new Traveller("P_A" + (i + 1), N, E, P));
}
// Start all traveler threads
for (Thread t : travellers) {
t.start();
}
// Wait for all traveler threads to finish
for (Thread t : travellers) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Discussion:
- Reads input parameters (totalEarth, totalProxima, and number of trips) from a file specified as a command-line argument.
- Creates an array of traveler threads and initializes them with the appropriate parameters.
- Starts all traveler threads concurrently.
- Waits for all traveler threads to complete using the join method.
Conclusion:
The program orchestrates a multithreaded simulation where travelers move back and forth between Earth and Proxima-b through a wormhole. The Traveller class encapsulates the behavior of a traveler, and the P1 class manages the execution of these travelers. The simulation is controlled by semaphores and atomic variables to ensure proper synchronization. Each traveler undergoes a series of steps while crossing the wormhole, and the program outputs details of their journeys and their overall progress. The number of travelers, their type, and the number of trips are read from an input file.
Related Samples
Explore our Java assignment samples for free! Gain insights into our approach and expertise in Java programming. See how we tackle various problems and deliver quality solutions. Discover what sets us apart in Java programming education and assistance.
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java