Aprendizado profundo em Java 20: sincronizado
Primeiro, observe um método comum sem decoração sincronizada
classe pública SynTest implementa Runnable { private static int count; public SynTest () { this .count = 0 ; } @Override public void run () { for ( int i = 0; i <5; i ++ ) { System.out.println (Thread.currentThread (). GetName () + ":" + ( contagem de ++ )); } } public static void main (String [] args) { SynTest synTest = new SynTest (); Thread thread1 = new Thread (synTest, "thread1" ); Thread thread2 = new Thread (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: Dois encadeamentos são concorrentes, competindo por recursos, fazendo com que (1) obtenha o mesmo valor (encadeamento1: 1 e encadeamento2: 1); (2) A ordem dos resultados de saída é incontrolável
1- Modifique um bloco de código
classe pública SynTest2 implementa Runnable { private static int count; public SynTest2 () { this .count = 0 ; } @Override public void run () { synchronized ( this ) { for ( int i = 0; i <5; i ++ ) { System.out.println (Thread.currentThread (). GetName () + ":" + (+ + contagem)); } } } Público estático vaziomain (String [] args) { // 1 SynTest2 synTest = new SynTest2 (); Thread thread1 = new Thread (synTest, "thread1" ); Thread thread2 = new Thread (synTest, "thread2" ); thread1.start (); thread2.start (); // 方式2 SynTest2 synTest1 = novo SynTest2 (); SynTest2 synTest2 = novo SynTest2 (); Thread thread3 = new Thread (synTest1, "thread3" ); Thread thread4= new Thread (synTest2, "thread4" ); thread3.start (); thread4.start (); } } ---------------------- Modo de execução separado 1 log ---------------------- thread1: 1 thread1: 2 thread1: 3 thread1: 4 thread1: 5 thread2: 6 thread2: 7 thread2: 8 thread2: 9 thread2: 10 ---------------------- Log de método de execução individual 2 ------------------- --- thread3: 1 thread4: 2 thread3: 3 thread4: 4 thread3: 5 thread3: 7 thread3: 8 thread4: 6 thread4: 9 thread4: 10
FIM