java synchronisation
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: java synchronisation

Hybrid View

  1. #1
    Join Date
    Apr 2011
    Posts
    2

    java synchronisation

    Hi,

    I am bit stuck here, I have to have edit this code so that a train must wait in front of the tunnel lock for a train to come in the opposite direction to exit before it can enter the tunnel, i have to use java built in synchronisation condition. Before the try statement I have tried looking at while statements, if statements and still cant get it to give me the following output:

    Train 1 arrives
    Train 1 ascends
    Train 1 Exits Tunnel
    Train 2 Arrives
    train 2 descends
    train 2 exits tunnel
    train 3 and so on


    Any help would be greatful

    public synchronized void useTunnelLock(Train train)
    {


    System.out.println(train + " " + train.getDirection());
    System.out.println(train + " exiting Tunnel");
    while(train.getDirection() == ASCENDING())
    {
    this.wait();
    }
    notifyAll();
    try
    {
    // occupy tunnel lock for 5s
    Thread.sleep(5000);
    }
    catch (InterruptedException ex)
    {
    ex.printStackTrace();
    }

    // swap direction of tunnel lock
    direction = (direction == ASCENDING)? DESCENDING : ASCENDING;
    }

  2. #2
    Join Date
    Apr 2011
    Posts
    2

    Re: java synchronisation

    Sorry i just realised i havent formatted the code correctly

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: java synchronisation

    Sorry i just realised i havent formatted the code correctly
    You need to use code tags, see my signature at the bottom of this post.

    I don't understand the logic of your code, surely you should only wake up the waiting threads once a train has exited the tunnel and not before it enters the tunnel. Your code has no logic to handle direction equaling DESCENDING, so what happens in this case. Another thing is what happens if more than one train is waiting to enter the tunnel?

    BTW why do you have a method called ASCENDING() or was this supposed to be just ASCENDING in which case how does this code even compile.

    Before you do any more coding clearly write down the sequence of steps you need to follow to get several trains through the tunnel and use this as the template for your code.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center