Una pregunta clásica de la entrevista: dos hilos, imprimen respectivamente AB, entre los cuales el hilo A imprime A, el hilo B imprime B, imprime 10 veces cada uno, de modo que el efecto de Abababa ...
paquete com.shangshe.path; public class threadab { / ** * @param args * / public static void main (string [] args) {final impresión comercial = new print (); new Thread (new Runnable () {public void run () {for (int i = 0; i <10; i ++) {Business.print_a ();}}}}). start (); New Thread (new Runnable () {public void run () {for (int i = 0; i <10; i ++) {Business.print_b ();}}}}). start (); }} clase impresa {bandera booleana privada = true; public sincronizado void print_a () {while (! flag) {try {this.wait (); } Catch (InterruptedException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); }} System.out.print ("A"); bandera = falso; this.notify (); } public sincronizado void print_b () {while (flag) {try {this.wait (); } Catch (InterruptedException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); }} System.out.print ("b"); bandera = verdadero; this.notify (); }}Del ejemplo anterior, podemos diseñar un programa con 3 hilos o incluso n hilos. El ejemplo que se detalla a continuación son 3 hilos, respectivamente, A, B y C se imprimen 10 veces, de modo que el efecto de ABCABC ..
public class ThreadAbc { / ** * @param args * / public static void main (string [] args) {final impresión de impresión = new print (); new Thread (new Runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_a ();}}}). start (); new Thread (new Runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_b ();}}}). start (); new Thread (new Runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_c ();}}}). Start (); }} clase impresa {private boolean debería_a = true; booleano privado debería_b = falso; privado booleano debería_c = falso; public sincronizado void print_a () {while (debería_b || debería_c) {try {this.wait (); } Catch (InterruptedException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); }} System.out.print ("A"); debería_a = falso; debería_b = verdadero; debería_c = falso; this.notifyall (); } public sincronizado void print_b () {while (debería_a || debería_c) {try {this.wait (); } Catch (InterruptedException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); }} System.out.print ("b"); debería_a = falso; debería_b = falso; debería_c = true; this.notifyall (); } public sincronizado void print_c () {while (debería_a || debería_b) {try {this.wait (); } Catch (InterruptedException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); }} System.out.print ("c"); debería_a = verdadero; debería_b = falso; debería_c = falso; this.notifyall (); }}Una vez más, se prueba la importancia de la ingeniería de software; En programas multiproceso, debe decirse que en los programas, debemos poner el código de la lógica de negocios en la misma clase para que sea altamente cohesivo y bajo acoplamiento