Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added lines to reset interrupted status

...

Code Block
bgColor#FFcccc
public class MissedSignal implements Runnable {
  private static final Object lock = new Object();
  private static int buffer_count = 5;
  private static int number; // Selects function based on thread number	
  
  public void run (){
    synchronized(lock) {
      try {    	  
        if(number == 1) {	  
          while(buffer_count == 0) { 
      	    lock.wait();		  
      	  }  
      	} else if(number == 2) {  	    		  
      	  while(buffer_count == 10) {	
      	    lock.wait();   	    		    	        	    
      	  }
      	} else if(number == 3) {	   
          lock.notify();      	   		  
        } 	    	  
      } catch (InterruptedException ie) {
        // Handle the exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      }
    }	  
  }

  public static void setThreadParameters(int threadNumber, int bufferCount) {
    number = threadNumber;
    buffer_count = bufferCount;
  }
                
  public static void main(String[] args) throws IOException, InterruptedException {    
    MissedSignal ms = new MissedSignal();
     
    for(int i = 0; i < 3; i++) {          // Buffer count does not matter for third thread
      setThreadParameters(i + 1, i * 10); // Sets buffer count for threads in the sequence: 0, 10, 20
      new Thread(ms).start();
      Thread.sleep(1000);
    }
  }
}

...

Code Block
bgColor#FFcccc
final Condition cond = lock.newCondition();
// ...

public void run (){
  lock.lock();  
  try {    	  
    if(number == 1) {	  
      while(buffer_count == 0) { 
        cond.await();		  
      }  
    } else if(number == 2) {  	    		  
      while(buffer_count == 10) {	
        cond.await();   	    		    	        	    
      }      
    } else if(number == 3) {
      cond.signal();	
    } 	   
  } catch (InterruptedException ie) {
      // Handle the exception
    Thread.currentThread().interrupt(); // Reset interrupted status
  } finally {
    lock.unlock();
  }
}	  

...

Code Block
bgColor#ccccff
final Lock lock = new ReentrantLock();
final Condition full = lock.newCondition();
final Condition empty = lock.newCondition();
// ...

public void run (){
  lock.lock();  
  try {    	  
    if(number == 1) {	  
      while(buffer_count == 0) { 
        empty.await();		  
      }  
    } else if(number == 2) {  	    		  
      while(buffer_count == 10) {	
        full.await();   	    		    	        	    
      }
    } else if(number == 3) {
      empty.signal();	
      full.signal();      	   		  
    } 	   
  } catch (InterruptedException ie) {
    // Handle the exception
    Thread.currentThread().interrupt(); // Reset interrupted status
  } finally {
    lock.unlock();
  }
}	  

...