Ver Mensaje Individual
  #6 (permalink)  
Antiguo 18/08/2011, 07:43
Avatar de Ronruby
Ronruby
 
Fecha de Ingreso: julio-2008
Ubicación: 18°30'N, 69°59'W
Mensajes: 4.879
Antigüedad: 15 años, 9 meses
Puntos: 416
Respuesta: Consulta synchronized objeto

Hice una pequena prueba para que verifiques como es que lo debes hacer:
Código Javascript:
Ver original
  1. public static void main(String[] args) throws Exception {
  2.         final SyncTest test = new SyncTest();
  3.  
  4.         Thread hiloUno = new Thread(new Runnable() {
  5.             public void run() {
  6.                 try {
  7.                     test.writeToFile("A");
  8.                 } catch(Exception e) {
  9.  
  10.                 }
  11.             }
  12.         });
  13.  
  14.         Thread hiloDos = new Thread(new Runnable() {
  15.             public void run() {
  16.                 try {
  17.                     test.writeToFile("B");
  18.                 } catch(Exception e) {
  19.  
  20.                 }
  21.             }
  22.         });
  23.  
  24.         hiloUno.start();
  25.         hiloDos.start();
  26.     }
Código Javascript:
Ver original
  1. public void writeToFile(String firstChar) {
  2.  
  3.         synchronized (SyncTest.archivo) {
  4.  
  5.             for(int i = 1; i <= 10; i++) {
  6.                  System.out.println(firstChar + i); //Debes reemplazar esto por la actual escritura
  7.             }
  8.  
  9.         }
  10.  
  11.     }

Debes de aislar el metodo de escritura en tu clase tambien

La clase SyncTest tiene un metodo llamado writeToFile que cree para hacer una pruebita. Al hacerlo de esa manera, solo un hilo escribira a la vez en el archivo.