1 Replies - 432 Views - Last Post: 22 March 2011 - 06:59 PM Rate Topic: -----

#1 kswith67  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 23-June 09

Java Concurrency Problem

Posted 22 March 2011 - 05:37 PM

My assignment requires to print Mares eat oats, Does eat oats, And little lambs eat ivy. In this order
I am able to print the first two but not the last message. When I debug it seems to stop at line 17.

Other Requirements....
All print statements must be in main.
All three message assignments must remain unchanged from Badthreads.java (code I'm modifying)
Must use wait/notify/join. Not sleep.


Below is what I have tried thus far. Any help will be appreciated. If I need to provide more information let me know.
FYI I'm very new to Java Concurrency.
public class BadThreads extends Thread {
  static String message;
  static boolean flag = false;
  private static final Object monitor = new Object();  // for synchronization
  // default empty constructor...

  public void run() {
   synchronized(monitor){
    message = "Mares eat oats."; 
    flag = true;
    monitor.notifyAll();
    try {
    	while(flag)
    		monitor.wait();
    } catch (InterruptedException e) {} 
   }
   	synchronized(monitor){
   	 	message = "And little lambs eat ivy.";
   	}
 }
  
  public static void main(String args[]) throws InterruptedException {
	(new BadThreads()).start();
	synchronized(monitor){
			try{
				while(!flag)
				monitor.wait();
			}catch (InterruptedException e) {}
	}
	synchronized(monitor){
		System.out.println(message);
    	message = "Does eat oats.";  
    	System.out.println(message);
    	flag = false;
    	monitor.notifyAll();
	}
	
		BadThreads.currentThread().join();
		System.out.println(message);

	
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Java Concurrency Problem

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: Java Concurrency Problem

Posted 22 March 2011 - 06:59 PM

Some misconceptions here

  public static void main(String args[]) throws InterruptedException {
        // this starts the thread 
	(new BadThreads()).start();
        // and probably get the lock on monitor before the Thread actually start
	synchronized(monitor){



  public void run() {
   // this is waiting fort the lock on monitor held by main() to be release before processing
   synchronized(monitor){
    message = "Mares eat oats."; 
    flag = true;


Also not a really good idea to symchonized(object) on an Object of type Object
*Edited: sorry seems ok this what they do in the Oracle's tutorials

Locks on a static variable are help on the whole class

This post has been edited by pbl: 22 March 2011 - 07:11 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1