user3316769
user3316769

Reputation: 1

traffic light program using java multithreading

i receive this "Exception in thread "main" java.lang.NullPointerException error" in two places which i will identify by using "->" i have traced the variables and i cant seem to find where it goes wrong.

//simulation.java




public class Simulation  {

private Thread thread1, thread2, thread3, thread4;


 public static void main(String[] args) {
    Simulation s = new Simulation();
  -> s.go();

}
   public void Simulation(){


    TrafficLight light = new TrafficLight();
    RoadRunnable road1 = new RoadRunnable(1, light);
    RoadRunnable road2 = new RoadRunnable(2, light);
    RoadRunnable road3 = new RoadRunnable(3, light);
    RoadRunnable road4 = new RoadRunnable(4, light);
    road1.add(" ");
    road2.add(" ");
    road3.add(" ");
    road4.add(" ");
    thread1 = new Thread((Runnable) road1);
    thread2 = new Thread((Runnable) road2);
    thread3 = new Thread((Runnable) road3);
    thread4 = new Thread((Runnable) road4);
}

 public void go() 
 {
->     thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
}

}



//roadrunnable.java

import java.util.LinkedList;





public class RoadRunnable extends TrafficLight implements Runnable {

private LinkedList<String> queue;
private int number;
private TrafficLight light;

public RoadRunnable(int roadNumber, TrafficLight aLight) {
    number = roadNumber;
    light = aLight;
    queue = new LinkedList();
}



public void run() {

    while (!queue.isEmpty()) {
        light.turnGreen(number);
        queue.remove();
    }

}

 public void add(String car) {

    for (int i = 0; i < 10; i++) {
        queue.add(car);
    }
}


}



//trafficlight.java




public class TrafficLight {


private int rNumber;


public TrafficLight() {
}


public void turnGreen(int roadNumber) {
    rNumber = roadNumber;
    synchronized (this) {

        System.out.print("Light turned green by road" + rNumber
                +"\n"
                + "Waiting for road" + rNumber + "car to clear intersection \n");

        for (int i = 10; (i >= 0); i--) {

            System.out.print(i + " ");

            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
            }
        }
        System.out.print("\n \n");
    }

}
}

Upvotes: 0

Views: 11833

Answers (1)

fgb
fgb

Reputation: 18559

public void Simulation() {
}

This is not a constructor. Constructors don't have a return type. Instead use:

public Simulation() {
}

Upvotes: 3

Related Questions