Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Threads and Synchronize
    text
    copied!<p>I'm working on a lab assignment and I'm a bit stuck on how to implement a specific class. My task is to create a program that simulates "Trolls" crossing a bridge. The Trolls are represented by threads. This is part of the Troll class I've written:</p> <pre><code>public class Troll implements Runnable { // instance variables // constructor public void run() { System.out.println( name + " has arrived at the bridge."); System.out.println( name + " is starting to cross."); // simulate crossing time for( int i = 1; i &lt;= crossingTime; ++i ) { try{ Thread.sleep( 1000 ); } catch( InterruptedException e ) {} System.out.println( "\t" + name + " " + i + " seconds." ); } System.out.println( name + " leaves at " + destination + "." ); } } </code></pre> <p>Now the part I'm stuck on is my "Bridge" class. The Bridge class is suppose to ensure only 1 Troll crosses the bridge at a time. The bridge class must only have these 2 methods with the same method signature:</p> <pre><code>//request permission to enter bridge public void enterBridge() {} //notify bridge that Troll is leaving public void leaveBridge() {} </code></pre> <p>The problem I'm having is figuring out how to make use of these methods. The hint I got from the instructions is to use synchronize. I believe this means to use a synchronized block in <code>enterBridge</code>, but I don't see how this would work. The code that simulates the actual crossing is in the Troll's run method (this is required by the lab). So to begin crossing, you have to exit the synchronized block. This would release the "lock" and then other trolls will begin crossing before the previous Troll has finished, which is not wanted.</p> <p>I don't really see the need of the Bridge methods in the first place, since I can just put the code in my Troll's run method in a synchronized block: </p> <pre><code>public void run() { System.out.println( name + " has arrived at the bridge."); synchronized( bridge ) { //Code from before } } </code></pre> <p>This ensures only one Trolls is crossing at a time without needing to call the Bridge class methods. So can someone tell me what the lab is getting at with the Bridge class? I feel like I'm overlooking something obvious or maybe I'm misunderstanding how synchronize works.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload