Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: The book I'm studying is wrong!

  1. #1
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Exclamation The book I'm studying is wrong!

    Hello,

    I'm learning java on my own and the example in the book to demonstrate threads and synchronization is not working. I'm not able to figure out why the sample will not run. Any ideas?


    public enum TrafficLightColor {
    RED,
    GREEN,
    YELLOW;
    }

    ***************>

    public class TrafficLightSimulator implements Runnable {
    private Thread thrd;
    private TrafficLightColor tlc;
    boolean stop = false;
    boolean changed = false;

    TrafficLightSimulator(TrafficLightColor init) {
    tlc = init;

    thrd = new Thread(this);
    thrd.start();
    }

    public void run() {
    while(!stop) {
    try {
    switch(tlc) {
    case GREEN:
    Thread.sleep(10000);
    break;
    case YELLOW:
    Thread.sleep(2000);
    break;
    case RED:
    Thread.sleep(12000);
    break;
    }
    } catch(InterruptedException exc) {
    System.out.println(exc);
    }
    changeColor();
    }
    }

    synchronized void changeColor() {
    switch(tlc) {
    case RED:
    tlc = TrafficLightColor.GREEN;
    break;
    case YELLOW:
    tlc = TrafficLightColor.RED;
    break;
    case GREEN:
    tlc = TrafficLightColor.YELLOW;
    }

    changed = true;
    notify();
    }

    synchronized void waitForChange() {
    try {
    while(!changed);
    wait();
    changed = false;
    } catch(InterruptedException exc) {
    System.out.println(exc);
    }
    }

    synchronized TrafficLightColor getColor() {
    return tlc;
    }

    synchronized void cancel() {
    stop = true;
    System.out.println("after stop changed. stop = " + stop);
    }
    }



    ***************>

    public class TrafficLightDemo {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.GREEN);

    for(int i=0; i<9; i++) {
    System.out.println(t1.getColor());
    t1.waitForChange(); //hanging here?
    }
    t1.cancel();
    }

    }

  2. #2
    Member
    Join Date
    May 2017
    Location
    Eastern Florida
    Posts
    68
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: The book I'm studying is wrong!

    the example in the book to demonstrate threads and synchronization is not working
    Please explain what happens. If there are error messages, copy the full text and paste it here.

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.

  3. #3
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    The output is "GREEN". Then it hangs. There is no error message. The output should be GREEN, YELLOW, RED (3 times).

  4. #4
    Member
    Join Date
    May 2017
    Location
    Eastern Florida
    Posts
    68
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: The book I'm studying is wrong!

    Please post the code wrapped in code tags so it can be copied and used for testing.

    It should look like this:
      // this is where your code should be

  5. #5
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    Sorry - first time posting. Thanks



    public enum TrafficLightColor {
    RED,
    GREEN,
    YELLOW;
    }
     
    /////////////////////////
     
    public class TrafficLightSimulator implements Runnable {
    private Thread thrd;
    private TrafficLightColor tlc;
    boolean stop = false;
    boolean changed = false;
     
    TrafficLightSimulator(TrafficLightColor init) {
    tlc = init;
     
    thrd = new Thread(this);
    thrd.start();
    }
     
    public void run() {
    while(!stop) {
    try {
    switch(tlc) {
    case GREEN:
    Thread.sleep(10000);
    break;
    case YELLOW:
    Thread.sleep(2000);
    break;
    case RED:
    Thread.sleep(12000);
    break;
    }
    } catch(InterruptedException exc) {
    System.out.println(exc);
    }
    changeColor();
    }
    }
     
    synchronized void changeColor() {
    switch(tlc) {
    case RED:
    tlc = TrafficLightColor.GREEN;
    break;
    case YELLOW:
    tlc = TrafficLightColor.RED;
    break;
    case GREEN:
    tlc = TrafficLightColor.YELLOW;
    }
     
    changed = true;
    notify();
    }
     
    synchronized void waitForChange() {
    try {
    while(!changed);
    wait();
    changed = false;
    } catch(InterruptedException exc) {
    System.out.println(exc);
    }
    }
     
    synchronized TrafficLightColor getColor() {
    return tlc;
    }
     
    synchronized void cancel() {
    stop = true;
    System.out.println("after stop changed. stop = " + stop);
    }
    }
     
     
     
    ////////////////////////
     
    public class TrafficLightDemo {
     
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.GREEN);
     
    for(int i=0; i<9; i++) {
    System.out.println(t1.getColor());
    t1.waitForChange(); //hanging here?
    }
    t1.cancel();
    }
     
    }

  6. #6
    Member
    Join Date
    May 2017
    Location
    Eastern Florida
    Posts
    68
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: The book I'm studying is wrong!

    That's some better, but still the indentations for the statements are missing. The statements should not all start in the first column. Proper indentation makes the code easier to read and understand.

    Then it hangs.
    What happens to the CPU usage? Does it show the program is doing anything or that the program is idle?
    Are there any loops in the code that could be looping endlessly? Add some print statements before and after all the loops to see if they aren't ending

  7. #7
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    Code hangs almost immediately and doesn't even complete it's first loop see main class. Java hangs as if it's waiting form something and cpu remains high. I have to do a ctrl+alt+delete in order to stop the app from hanging. memory is 5,496K and CPU is 49


     
    public enum TrafficLightColor {
    	RED, 
    	GREEN, 
    	YELLOW;
    }
     
    public class TrafficLightSimulator implements Runnable {
    	private Thread thrd;
    	private TrafficLightColor tlc;
    	boolean stop = false;
    	boolean changed = false;
     
    	TrafficLightSimulator(TrafficLightColor init)	{
    		tlc = init;
     
    		thrd = new Thread(this);
    		thrd.start();
    	}
     
    	public void run() {
    		while(!stop) {
    			try {
    				switch(tlc) {
    				case GREEN:
    					Thread.sleep(10000);
    					break;
    				case YELLOW:
    					Thread.sleep(2000);
    					break;
    				case RED:
    					Thread.sleep(12000);
    					break;
    			}
    			} catch(InterruptedException exc)	{
    				System.out.println(exc);
    			}
    			changeColor();
    		}
    	}
     
    	synchronized void changeColor()	{
    		switch(tlc)	{
    		case RED:
    			tlc = TrafficLightColor.GREEN;
    			break;
    		case YELLOW:
    			tlc = TrafficLightColor.RED;
    			break;
    		case GREEN:
    			tlc = TrafficLightColor.YELLOW;
    		}
     
    		changed = true;
    		notify();
    	}
     
    		synchronized void waitForChange()	{
    			try {
    				while(!changed);
    					wait();
    				changed = false;
    			} catch(InterruptedException exc) {
    				System.out.println(exc);
    			}
    		}
     
    		synchronized TrafficLightColor getColor() {
    			return tlc;
    		}
     
    		synchronized void cancel()	{
    			stop = true;
    			System.out.println("after stop changed. stop =  " + stop);
    	}
    }
     
     
    ///////////////////////////Main PRG
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		 TrafficLightSimulator t1 =	new TrafficLightSimulator(TrafficLightColor.GREEN);
     
    		 for(int i=0; i<9; i++) {
    			System.out.println(t1.getColor() + "   loop "+ i);
    			t1.waitForChange(); //hanging here. Doesn't complete loop.
    					    //Doesn't go into waitForChange()
    		 }
    		 t1.cancel();
    	}
     
    }

  8. #8
    Member
    Join Date
    May 2017
    Location
    Eastern Florida
    Posts
    68
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: The book I'm studying is wrong!

    Ok, that formatting looks a lot better.
    I see two while loops that don't have print statements before, inside and and after them to show when and where they are executing.
    Be sure to add print statements around ALL the loops.

    CPU is 49
    That says there is a loop that is running continuously without doing enough work to slow it down some. The print statements will help you find it by printing thousands of lines as the loop goes around.

  9. #9
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    Quote Originally Posted by NormR View Post
    Ok, that formatting looks a lot better.
    I see two while loops that don't have print statements before, inside and and after them to show when and where they are executing.
    Be sure to add print statements around ALL the loops.


    That says there is a loop that is running continuously without doing enough work to slow it down some. The print statements will help you find it by printing thousands of lines as the loop goes around.
    Thanks. I assumed it was hanging on the 1st loop. I'll put print statements in all loops and get back to you.

  10. #10
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    Quote Originally Posted by MsNovice View Post
    Thanks. I assumed it was hanging on the 1st loop. I'll put print statements in all loops and get back to you.
    The following is the output when I run the code with messages within loops to output:

    In !stop while loop
    Sleeping in GREEN
    Before changeColor

    It hanges in or trying to go into changedColor. Possibly tlc's value is lost once in changedColor? If so, shouldn't I get an error? Value is seen and is GREEN prior to changeColor call.

     
    public enum TrafficLightColor {
    	RED, 
    	GREEN, 
    	YELLOW;
    }
     
     
    ///////////////////////////
    	public class TrafficLightSimulator implements Runnable {
    	private Thread thrd;
    	private TrafficLightColor tlc;
    	boolean stop = false;
    	boolean changed = false;
     
    	TrafficLightSimulator(TrafficLightColor init)	{
    		tlc = init;
     
    		thrd = new Thread(this);
    		thrd.start();
    	}
     
    	public void run() {
    		while(!stop) {
    			System.out.println("In !stop while loop");
    			try {
    				switch(tlc) {
    				case GREEN:
    					System.out.println("Sleeping in GREEN");
    					Thread.sleep(100);
    					break;
    				case YELLOW:
    					System.out.println("Sleeping in YELLOW");
    					Thread.sleep(20);
    					break;
    				case RED:
    					System.out.println("Sleeping in RED");
    					Thread.sleep(120);
    					break;
    			}
    			} catch(InterruptedException exc)	{
    				System.out.println(exc);
    			}
    			System.out.println("Before changeColor. Value of tlc is " + tlc);
    			changeColor();
    		}
    	}
     
    	synchronized void changeColor()	{
    		System.out.println("In changeColor");
    		switch(tlc)	{
    		case RED:
    			System.out.println("Changing to GREEN");
    			tlc = TrafficLightColor.GREEN;
    			break;
    		case YELLOW:
    			System.out.println("Changing to RED");
    			tlc = TrafficLightColor.RED;
    			break;
    		case GREEN:
    			System.out.println("Changing to YELLOW");
    			tlc = TrafficLightColor.YELLOW;
    		}
     
    		changed = true;
    		System.out.println("Changed = " + changed);
    		notify();
    	}
     
    		synchronized void waitForChange()	{
    			try {
    				while(!changed);
    					System.out.println("In synchronized while loop !changed");
    					wait();
    				changed = false;
    			} catch(InterruptedException exc) {
    				System.out.println(exc);
    			}
    		}
     
    		synchronized TrafficLightColor getColor() {
    			return tlc;
    		}
     
    		synchronized void cancel()	{
    			stop = true;
    			System.out.println("after stop changed. stop =  " + stop);
    	}
    }
     
    //////////////////////////////
     
    public class TrafficLightDemo {
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		 TrafficLightSimulator t1 =	new TrafficLightSimulator(TrafficLightColor.GREEN);
     
    		 for(int i=0; i<9; i++) {
    			System.out.println(t1.getColor() + "   for loop of main "+ i);
    			t1.waitForChange(); //hanging here. Doesn't complete loop.
    		 }
    		 t1.cancel();
    	}
     
    }

  11. #11
    Member
    Join Date
    May 2017
    Location
    Eastern Florida
    Posts
    68
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: The book I'm studying is wrong!

    I still don't see a print statement in the waitForChange() method before the while statement.

    while(!changed);
    Note: the ; after the ) ends the while statement. None of the following statements are in the loop.
    There needs to be {}s around the statements that are supposed to be inside the loop.
    Last edited by NormR; June 1st, 2017 at 07:59 PM.

  12. The Following User Says Thank You to NormR For This Useful Post:

    MsNovice (June 3rd, 2017)

  13. #12
    Junior Member
    Join Date
    May 2017
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: The book I'm studying is wrong!

    THAT WAS IT!!!!! Thanks so much for the debugging lesson and finding the error!!!!

  14. #13
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: The book I'm studying is wrong!

    I'm glad that's fixed your problem. Please go ahead and mark the thread as solved! Should be an option available to you, see this post http://www.javaprogrammingforums.com...ad-solved.html for guidance.

Similar Threads

  1. [SOLVED] As a self-studying student, I need moderators to mark assignment.
    By LittleCat in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 16th, 2012, 09:31 AM
  2. Help regarding choosing J2EE book for studying
    By rohan22 in forum Java Servlet
    Replies: 1
    Last Post: May 1st, 2012, 02:02 AM
  3. Studying for a test, can't figure out my code won't work
    By coolidge in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 27th, 2011, 01:12 PM
  4. Replies: 6
    Last Post: July 21st, 2011, 07:45 AM
  5. Is my book bad or am I doing 'wrong'?
    By Catgroove in forum Java Theory & Questions
    Replies: 6
    Last Post: November 16th, 2010, 02:51 PM