HI, aLL

final int[] fromStop = {1, 2, 3, 3, 4, 5};
          final int[] toStop =   {3, 4, 5, 1, 2, 3};

im trying to write a loop to create and start passenger threads
with the respective from and to stops in the arrays above.
e.g. Passenger 1 goes from stop 1 to stop 3 etc

class Passenger extends Thread
{
  
  private int id;       // unique id, from 1 to Main.PASSENGERS
  private int from, to; // start and end bus stops 
  private Bus bus;
  
    
  Passenger(int id, int from, int to, Bus bus)
  { 
    this.id = id;
    this.from = from; 
    this.to = to; 
    this.bus = bus;    
     
  }

Can anyone help???

Recommended Answers

All 9 Replies

Thanks for your post.

This is the run() method. How do i apply it to a loop that creates and runs the Passenger Threads?

Passenger(int id, int from, int to, Bus bus)
  { 
    this.id = id;
    this.from = from; 
    this.to = to; 
    this.bus = bus;    
     
  }
  
  public void run()
  {
    System.out.println(Main.spaces(from) + 'P' + id + " arrives");
   
    bus.getOn(from);
    System.out.println(Main.spaces(from) + 'P' + id + " gets on");
    
    bus.getOff(to);
    System.out.println(Main.spaces(to) + 'P' + id + " gets off");
final int[] fromStop = {1, 2, 3, 3, 4, 5};
final int[] toStop =   {3, 4, 5, 1, 2, 3};

List<Passenger> passengers = new ArrayList<Passenger>()
for (int i = 1; i < Main.PASSENGERS; i++) {
    bus = // get the bus you want the passenger to take
    Passenger passenger =  new Passenger(i, fromStop[i - 1], toStop[i - 1], bus);
    passengers.append(passenger);
    passenger.start()
}

// Wait for every passenger to finish
for (Passenger passenger: passengers) {
    if (passenger.isAlive()) {
         passenger.join();       
    }
}

Think that should do the trick.

Well, that seems to solve that problem :cool: Thankyou for all your time, im verry greatful.

Hi, im trying to get code that if seats are availabile on a bus, then a passenger may get on. For the code i have provided, when i run it ,passenger gets on at the correct stop, but never get off.....i.e. the first 2 passengers ride forever........ help! what am i doing wrong?

private int position;    // bus's currrent position, i.e. bus stop.
private int available;   // available seats
available = Main.CAPACITY; //  located in bus constructor.
public final static int CAPACITY = 2; // located in class main.
-----------------------------------------------------------------------------------

// Method called by passengers wishing to get ON the bus at bus stop


public void getOn(int fromStop)
  {    
    bus.lock();  // passenger obtains the resource.
//passenger waits until the bus is at the bus stop and a seat is available.
   try
   {
       while(fromStop < position || fromStop > position ||
available == Main.CAPACITY-2) 
       {
           wantingOn.await();
       }
       available--;   // passenger gets on the bus
       wantingOff.signal();
   }
       catch (InterruptedException e)
       {}
       finally
       {           
      // passenger releases the resource
           bus.unlock();
        }
    }
   
   


  // Method called by passengers wishing to get off the bus at bus stop.
  public void getOff(int toStop) 
  {
    //  passenger obtains the resource.
  bus.lock();

  try
  {
    // passenger waits until the bus is at the bus stop.
    while(toStop != position)
    {
        wantingOff.await();
    }
    available++;
    wantingOn.signal();
  }
    catch (InterruptedException e)
    {}
    finally
    {
    // passenger releases the resource
        bus.unlock();
    }
  }

It's quite hard to see what's going on, since you only posted a part of your code. We can't see what's going on outside the methods, who is calling the methods, when they are called etc.

One minor thing.

while(fromStop < position || fromStop > position || available == Main.CAPACITY-2)

could be rewritten as while(fromStop != position || available == 0) . If you ever change the Main.CAPACITY value, your original while-loop will fail.

Post more of your code, and I might be able to help you

Hi

Ok, here's the lot, I have a package with 4 classes.

Bus,Control,Main & passenger.

Im trying to get passengers to board the bus if it arives at their stop and there is enough seats. there is a max of 2 seats. Also, each passenger only rides till the 2nd Stop.

At the moment, when i run it, 1 passenger at a time gets on and only at every 5th . However....... they are geting off at their correct stops. Here is a Section of my output....

compile:
run:
                                  Bus Stops
      1---------------2---------------3---------------4---------------5
[..]BUS> arrives
P1 arrives
P1 gets on
                                P3 arrives
                                                P5 arrives
                P2 arrives
                                P4 arrives
[*.]BUS> leaves
                [*.]BUS> arrives
                [*.]BUS> leaves
                                [*.]BUS> arrives
                                P1 gets off
                                [..]BUS> leaves
                                                [..]BUS> arrives
                                                [..]BUS> leaves
                                                                [..]BUS> arrives
                                                                <BUS[..] leaves
                                                <BUS[..] arrives
                                                P5 gets on
                                                <BUS[.*] leaves
                                <BUS[.*] arrives
                                <BUS[.*] leaves
                <BUS[.*] arrives
                P5 gets off
                <BUS[..] leaves
<BUS[..] arrives
[..]BUS> leaves
                [..]BUS> arrives
                [..]BUS> leaves
                                [..]BUS> arrives
                                P3 gets on
                                [*.]BUS> leaves
                                                [*.]BUS> arrives
                                                [*.]BUS> leaves
                                                                [*.]BUS> arrives
                                                                P3 gets off
                                                                <BUS[..] leaves
                                                <BUS[..] arrives
                                                <BUS[..] leaves
                                <BUS[..] arrives
                                <BUS[..] leaves
                <BUS[..] arrives
                <BUS[..] leaves
<BUS[..] arrives
[..]BUS> leaves
                [..]BUS> arrives
                [..]BUS> leaves
                                [..]BUS> arrives
                                [..]BUS> leaves

/B]

--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
----*:'( HERE IS THE CODE FOR THE 4 CLASSES:'( -------------------


package busservice;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Bus
{
public enum Direction{UP, DOWN};

private int position; // bus's currrent position, i.e. bus stop.
private int increment; // bus's currrent increment +1 for UP, -1 for DOWN
private Direction busDirection;// bus's current direction - UP or DOWN
private int available; // available seats
private ReentrantLock bus = new ReentrantLock();
private Condition[] arrive = new Condition[Main.BUS_STOPS+1]; // index 0 unused
private Condition wantingOff = bus.newCondition();
private Condition wantingOn = bus.newCondition();
public Bus()
{
available = Main.CAPACITY;
position = 1;
increment = 1; // Initially travelling in UP direction
busDirection = Direction.UP;
System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
for (int i = 1; i <= Main.BUS_STOPS; i++)
arrive = bus.newCondition();
}

// method called by a passenger wishing to get on the bus at bus stop
public void getOn(int fromStop)
{
// code so that passenger obtains the resource.

bus.lock();
// code so that passenger waits until the bus is at the bus stop.
try
{
while(fromStop != position || available == 0)
{
wantingOn.await();

}
available--;// passenger gets on the bus
wantingOff.signal();
}
catch (InterruptedException e)
{
}


finally
{

// code so that passenger releases the resource

bus.unlock();

}


}
// Method called by passengers wishing to get off the bus at bus stop.
public void getOff(int toStop)
{
// code so that passenger obtains the resource.
bus.lock();

try
{
// code so that passenger waits until the bus is at the bus stop.
while(toStop != position)// || toStop > position)
{
wantingOff.await();
}
available++;
wantingOn.signal();
}
catch (InterruptedException e)
{}
finally
{
// code so that passenger releases the resource
bus.unlock();
}
}

// returns a string showing the direction and occupancy status of the bus
private String labelledBus()
{
String emptySeats = "...................".substring(0, available);
String fullSeats = "*******************".substring(0, Main.CAPACITY - available);

if (busDirection == Direction.DOWN)
{
return ("<BUS["+emptySeats+fullSeats+"]");
}
else
{
return ("["+fullSeats+emptySeats+"]BUS>");
}
}

// Method called by control system to move bus to next bus stop
public void move()
{
//code so that control system obtains resource
bus.lock();
try // bus leaves one bus stop and travels to next one
{
System.out.println(Main.spaces(position) + labelledBus()+" leaves");
Thread.sleep(Main.TRAVEL_TIME * 1000);
position = position + increment;
System.out.println(Main.spaces(position) + labelledBus()+ " arrives");

// Reverse direction if at end of route
if ((busDirection == Direction.UP) && position == Main.BUS_STOPS)
{
increment = - increment;
busDirection = Direction.DOWN;
}
else if ((busDirection == Direction.DOWN) && position == 1)
{
increment = - increment;
busDirection = Direction.UP;
}

// insert code to notify passengers getting on or off the bus at new bus stop.
wantingOff.signal();
wantingOn.signal();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}

// insert code so that control system releases the resource
bus.unlock();

}
}
:S --------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------


package busservice;

class Control extends Thread
{
private Bus bus;
private volatile boolean end = false;

public Control(Bus bus)
{
this.bus = bus;
}

public void run()
{
while (!end)
{
try
{
sleep(Main.WAIT_TIME * 1000);
bus.move();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
return;
}
}
}

public void finish()
{
end = true;
}

}

:X --------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------


package busservice;

// any necessary import directives here
import java.util.*;
class Main
{
// number of bus stops
public final static int BUS_STOPS = 5;
// bus waiting time (in seconds) at each bus stop
public final static int WAIT_TIME = 1;
// bus travel time (in seconds) between bus stops
public final static int TRAVEL_TIME = 1;
// bus capacity (number of passengers)
public final static int CAPACITY = 2;
// number of passengers in system
public final static int PASSENGERS = 6;

// Align output message according to bus stop where event happens.
public static String spaces (int busStop)
{
return "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t".substring(0, 2*(busStop-1));
}

public static void main(String[] args)
{
System.out.println("\t\t\t\t Bus Stops");
System.out.print(" 1");
for (int i = 2; i <= BUS_STOPS; i++)
System.out.print("---------------" + i);
System.out.println();

Bus bus = new Bus();
Control control = new Control(bus);

control.start(); // Start the control system.

// Define departure and destination stops for each passenger
final int[] fromStop = {1, 2, 3, 3, 4, 5};
final int[] toStop = {3, 4, 5, 1, 2, 3};

// loop to create and start passenger threads
// with the respective from and to stops in the arrays above.
// e.g. Passenger 1 goes from stop 1 to stop 3 etc
/*

List<Passenger> passengers = new ArrayList<Passenger>();

for (int i = 1; i < Main.PASSENGERS; i++)
{

bus = bus; // get the bus you want the passenger to take

Passenger passenger = new Passenger(i, fromStop, toStop, bus);

//passengers.append(passenger);

passenger.start();

}

// Wait for every passenger to finish

for (Passenger passenger: passengers) {

if (passenger.isAlive());
{
try {

passenger.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}

}

}

:-/ --------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------


package busservice;

class Passenger extends Thread
{

private int id; // unique id, from 1 to Main.PASSENGERS
private int from, to; // start and end bus stops
private Bus bus;


Passenger(int id, int from, int to, Bus bus)
{
this.id = id;
this.from = from;
this.to = to;
this.bus = bus;

}

public void run()
{
System.out.println(Main.spaces(from) + 'P' + id + " arrives");

bus.getOn(from);
System.out.println(Main.spaces(from) + 'P' + id + " gets on");

bus.getOff(to);
System.out.println(Main.spaces(to) + 'P' + id + " gets off");

//code to signal to the main thread that this passenger has finished..???????????????????????:?:
}
}


// code to wait for all passengers to get off bus at their destinations.?????????????????????:?:


// code to tell control system to finish.????????????:?:

}
}

Hehe. I really want to help you, but it's darn difficult. If you can either
- Fix the code so it's in tags (and make sure the code compile) - Attach the java files

I tried to cut'n'paste the code into Eclipse, but it wouldn't cooperate at all.

I noticed one thing, though. You should try to rethink your design. As it is now - every class is dependent on the other classes. Not one of them works without having the others present, and that's not good. Circular dependencies are the root of many bugs :)[code=java] tags (and make sure the code compile)
- Attach the java files

I tried to cut'n'paste the code into Eclipse, but it wouldn't cooperate at all.

I noticed one thing, though. You should try to rethink your design. As it is now - every class is dependent on the other classes. Not one of them works without having the others present, and that's not good. Circular dependencies are the root of many bugs :)

OOPS! :D

Here it is using

tags..  :) 




[code=java]package busservice;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Bus
{
public enum Direction{UP, DOWN};

private int position; // bus's currrent position, i.e. bus stop.
private int increment; // bus's currrent increment +1 for UP, -1 for DOWN
private Direction busDirection;// bus's current direction - UP or DOWN
private int available; // available seats
private ReentrantLock bus = new ReentrantLock();
private Condition[] arrive = new Condition[Main.BUS_STOPS+1]; // index 0 unused
private Condition wantingOff = bus.newCondition();
private Condition wantingOn = bus.newCondition();
public Bus()
{
available = Main.CAPACITY;
position = 1;
increment = 1; // Initially travelling in UP direction
busDirection = Direction.UP;
System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
for (int i = 1; i <= Main.BUS_STOPS; i++)
arrive[i] = bus.newCondition();
}



// method called by a passenger wishing to get on the bus at bus stop
public void getOn(int fromStop)
{
// code so that passenger obtains the resource.

bus.lock();
// code so that passenger waits until the bus is at the bus stop.
try
{
while(fromStop != position || available == 0)
{
wantingOn.await();

}
available--;// passenger gets on the bus
wantingOff.signal();
}
catch (InterruptedException e)
{
}


finally
{

// code so that passenger releases the resource

bus.unlock();

}


}
// Method called by passengers wishing to get off the bus at bus stop.
public void getOff(int toStop)
{
// code so that passenger obtains the resource.
bus.lock();

try
{
// code so that passenger waits until the bus is at the bus stop.
while(toStop != position)// || toStop > position)
{
wantingOff.await();
}
available++;
wantingOn.signal();
}
catch (InterruptedException e)
{}
finally
{
// code so that passenger releases the resource
bus.unlock();
}
}

// returns a string showing the direction and occupancy status of the bus
private String labelledBus()
{
String emptySeats = "...................".substring(0, available);
String fullSeats = "*******************".substring(0, Main.CAPACITY - available);

if (busDirection == Direction.DOWN)
{
return ("<BUS["+emptySeats+fullSeats+"]");
}
else
{
return ("["+fullSeats+emptySeats+"]BUS>");
}
}

// Method called by control system to move bus to next bus stop
public void move()
{
//code so that control system obtains resource
bus.lock();
try // bus leaves one bus stop and travels to next one
{
System.out.println(Main.spaces(position) + labelledBus()+" leaves");
Thread.sleep(Main.TRAVEL_TIME * 1000);
position = position + increment;
System.out.println(Main.spaces(position) + labelledBus()+ " arrives");

// Reverse direction if at end of route
if ((busDirection == Direction.UP) && position == Main.BUS_STOPS)
{
increment = - increment;
busDirection = Direction.DOWN;
}
else if ((busDirection == Direction.DOWN) && position == 1)
{
increment = - increment;
busDirection = Direction.UP;
}

// insert code to notify passengers getting on or off the bus at new bus stop.
wantingOff.signal();
wantingOn.signal();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}

// insert code so that control system releases the resource
bus.unlock();

}
}
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------


package busservice;

class Control extends Thread
{
private Bus bus;
private volatile boolean end = false;

public Control(Bus bus)
{
this.bus = bus;
}

public void run()
{
while (!end)
{
try
{
sleep(Main.WAIT_TIME * 1000);
bus.move();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
return;
}
}
}

public void finish()
{
end = true;
}

}

--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------


package busservice;

// any necessary import directives here
import java.util.*;
class Main
{
// number of bus stops
public final static int BUS_STOPS = 5;
// bus waiting time (in seconds) at each bus stop
public final static int WAIT_TIME = 1;
// bus travel time (in seconds) between bus stops
public final static int TRAVEL_TIME = 1;
// bus capacity (number of passengers)
public final static int CAPACITY = 2;
// number of passengers in system
public final static int PASSENGERS = 6;

// Align output message according to bus stop where event happens.
public static String spaces (int busStop)
{
return "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t".substring(0, 2*(busStop-1));
}

public static void main(String[] args)
{
System.out.println("\t\t\t\t Bus Stops");
System.out.print(" 1");
for (int i = 2; i <= BUS_STOPS; i++)
System.out.print("---------------" + i);
System.out.println();

Bus bus = new Bus();
Control control = new Control(bus);

control.start(); // Start the control system.

// Define departure and destination stops for each passenger
final int[] fromStop = {1, 2, 3, 3, 4, 5};
final int[] toStop = {3, 4, 5, 1, 2, 3};

// loop to create and start passenger threads
// with the respective from and to stops in the arrays above.
// e.g. Passenger 1 goes from stop 1 to stop 3 etc


List<Passenger> passengers = new ArrayList<Passenger>();

for (int i = 1; i < Main.PASSENGERS; i++)
{

bus = bus; // get the bus you want the passenger to take

Passenger passenger = new Passenger(i, fromStop[i - 1], toStop[i - 1], bus);

//passengers.append(passenger);

passenger.start();

}



// Wait for every passenger to finish

for (Passenger passenger: passengers) {

if (passenger.isAlive());
{
try {

passenger.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}

}

}

--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------




package busservice;

class Passenger extends Thread
{

private int id; // unique id, from 1 to Main.PASSENGERS
private int from, to; // start and end bus stops
private Bus bus;


Passenger(int id, int from, int to, Bus bus)
{
this.id = id;
this.from = from;
this.to = to;
this.bus = bus;

}

public void run()
{
System.out.println(Main.spaces(from) + 'P' + id + " arrives");

bus.getOn(from);
System.out.println(Main.spaces(from) + 'P' + id + " gets on");

bus.getOff(to);
System.out.println(Main.spaces(to) + 'P' + id + " gets off");

//Unfinnished Code TO DO..

//code to signal to the main thread that this passenger has finished..???????????????????????
}
}




// code to wait for all passengers to get off bus at their destinations.?????????????????????


// code to tell control system to finish.????????????

}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.