// Fig. 23.17: RunnableObject.java
// Runnable que grava um caractere aleatório em um JLabel
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.Color;

public class RunnableObject implements Runnable
{
   private static Random generator = new Random(); // para letras aleatórias
   private Lock lockObject; // bloqueio de aplicativo; passado para o construtor
   private Condition suspend; // utilizado para suspender e retomar thread
   private boolean suspended = false; // true se a thread for suspensa
   private JLabel output; // JLabel para a saída

   public RunnableObject( Lock theLock, JLabel label )
   {
      lockObject = theLock; // armazena o Lock para o aplicativo
      suspend = lockObject.newCondition(); // cria nova Condition
      output = label; // armazena JLabel para gerar saída de caractere
   } // fim do construtor RunnableObject

   // coloca os caracteres aleatórios na GUI
   public void run()                
   {
      // obtém nome de thread em execução
      final String threadName = Thread.currentThread().getName();

      while ( true ) // loop infinito; será terminado de fora 
      {
         try 
         {
            // dorme por até 1 segundo
            Thread.sleep( generator.nextInt( 1000 ) ); 

            lockObject.lock(); // obtém o bloqueio
            try
            {
               while ( suspended ) // faz loop até não ser suspenso
               {
                  suspend.await(); // suspende a execução do thread
               } // fim do while
            } // fim do try
            finally
            {
               lockObject.unlock(); // desbloqueia o bloqueio
            } // fim de finally
         } // fim do try
         // se a thread foi interrompida durante espera/enquanto dormia
         catch ( InterruptedException exception ) 
         {
            exception.printStackTrace(); // imprime o rastreamento de pilha
         } // fim do catch
            
         // exibe o caractere no JLabel correspondente
         SwingUtilities.invokeLater(                 
            new Runnable()                           
            {
               // seleciona o caractere aleatório e o exibe
               public void run()                      
               {
                  // seleciona a letra maiúscula aleatória
                  char displayChar = 
                     ( char ) ( generator.nextInt( 26 ) + 65 );

                  // gera saída de caractere em JLabel
                  output.setText( threadName + ": " + displayChar );
               } // fim do método run
            } // fim da classe inner
         ); // fim da chamada para SwingUtilities.invokeLater
      } // fim do while
   } // fim do método run

   // altera o estado suspenso/em execução
   public void toggle()
   {
      suspended = !suspended; // alterna booleano que controla estado

      // muda cor de rótulo na suspensão/retomada
      output.setBackground( suspended ? Color.RED : Color.GREEN );

      lockObject.lock(); // obtém bloqueio
      try
      {
         if ( !suspended ) // se a thread foi retomada
         {
            suspend.signal(); // retoma a thread
         } // fim do if
      } // fim do try
      finally
      {
         lockObject.unlock(); // libera o bloqueio
      } // fim de finally
   } // fim do método toggle
} // fim da classe RunnableObject 


/**************************************************************************
 * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/