Java Deep Learning 20: sincronizado

Java Deep Learning 20: sincronizado

 

Primer vistazo a un método común sin decoración sincronizada

 

público  de clase Syntest implementos   Runnable {
     privada  estática  int count;
    pública Syntest () {
         este .count = 0 ; 
    } 
    @Override 
    public  void run () {
         for ( int i = 0; i <5; i ++ ) { 
            System.out.println (Thread.currentThread (). GetName () + ":" + (++ count)); 
        } 
    } 
    public  static  void main (String [] args) { 
        SynTest synTest = new SynTest ();
        Thread thread1 = nuevo Thread (synTest, "thread1" ); 
        Subproceso thread2 = nuevo subproceso (synTest, "thread2" ); 
        thread1.start (); 
        thread2.start (); 
    } 
}
 --------------------- 日志 -------------------------- 
thread1: 1 
thread2: 1 
thread1: 2 
thread2: 3 
thread2: 5 
thread2: 6 
thread1: 4 
thread2: 7 
thread1: 8 
thread1: 9

 

Problema: Dos hilos son concurrentes, compitiendo por recursos, haciendo que (1) obtenga el mismo valor (hilo1: 1 y hilo2: 1); (2) El orden de los resultados de salida es incontrolable

 

1- Modificar un bloque de código

La  clase pública SynTest2 implementa   Runnable {
     recuento int privado  estático  ;
    pública SynTest2 () {
         este .count = 0 ; 
    } 
    @Override public void run () {
         sincronizado ( esto ) {
             para ( int i = 0; i <5; i ++ ) { 
                System.out.println (Thread.currentThread (). GetName () + ":" + (+ + cuenta)); 
            } 
        } 
    } vacío público estático
     
      main (String [] args) {
         // 
        方式1 SynTest2 synTest = new SynTest2 (); 
        Thread thread1 = nuevo Thread (synTest, "thread1" ); 
        Subproceso thread2 = nuevo subproceso (synTest, "thread2" ); 
        thread1.start (); 
        thread2.start (); 

        // 
        方式2 SynTest2 synTest1 = new SynTest2 (); 
        SynTest2 synTest2 = nuevo SynTest2 (); 
        Hilo thread3 = nuevo hilo (synTest1, "thread3" ); 
        Hilo thread4= nuevo subproceso (synTest2, "thread4" ); 
        thread3.start (); 
        thread4.start (); 
    } 
}
 ---------------------- Modo de ejecución independiente 1 registro ---------------------- 
hilo1: 1 
hilo1: 2 
hilo1: 3 
hilo1: 4 
hilo1: 5 
hilo2: 6 
hilo2: 7 
hilo2: 8 
hilo2: 9 
thread2: 10 
---------------------- Método de ejecución individual 2 log ------------------- --- 
thread3: 1 
thread4: 2 
thread3: 3 
thread4: 4
thread3: 5 
thread3: 7 
thread3: 8 
thread4: 6 
thread4: 9 
thread4: 10

 

 

 

FIN

Supongo que te gusta

Origin www.cnblogs.com/wobuchifanqie/p/12758338.html
Recomendado
Clasificación