Uma pergunta clássica da entrevista: dois tópicos, respectivamente, impressos AB, entre os quais Thread A impressões A, Thread B impressa B, imprime 10 vezes cada, para que o efeito de Abababa ...
pacote com.shangshe.path; classe pública threadab { / ** * @param args * / public static void main (string [] args) {Final Print Business = new Print (); novo thread (novo runnable () {public void run () {for (int i = 0; i <10; i ++) {Business.print_a ();}}}}). start (); novo thread (novo runnable () {public void run () {for (int i = 0; i <10; i ++) {Business.print_b ();}}}}). start (); }} classe Print {private boolean sinalizador = true; public sincronizado void print_a () {while (! flag) {tente {this.wait (); } catch (interruptedException e) {// TODO BLOCO DE CATCH AUTOGERATIDO E.PRINTSTACKTRACE (); }} System.out.print ("A"); bandeira = false; this.Notify (); } public sincronizado void print_b () {while (flag) {try {this.wait (); } catch (interruptedException e) {// TODO BLOCO DE CATCH AUTOGERATIDO E.PRINTSTACKTRACE (); }} System.out.print ("B"); bandeira = true; this.Notify (); }}A partir do exemplo acima, podemos projetar um programa com 3 threads ou até n threads. O exemplo dado abaixo são 3 threads, respectivamente, A, B e C são impressos 10 vezes, de modo que o efeito do ABCABC ..
classe pública threadabc { / ** * @param args * / public static void main (string [] args) {final de impressão Business = new Print (); novo thread (novo runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_a ();}}}). start (); novo thread (novo runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_b ();}}}). start (); novo thread (novo runnable () {public void run () {for (int i = 0; i <100; i ++) {Business.print_c ();}}}). start (); }} class Print {private boolean deve_a = true; Privado booleano deve_b = false; private boolean deve_c = false; public sincronizado void print_a () {while (deve_b || deve_c) {try {this.wait (); } catch (interruptedException e) {// TODO BLOCO DE CATCH AUTOGERATIDO E.PRINTSTACKTRACE (); }} System.out.print ("A"); deve_a = false; deve_b = true; deve_c = false; this.NotifyAll (); } public sincronizado void print_b () {while (deve_a || deve_c) {try {this.wait (); } catch (interruptedException e) {// TODO BLOCO DE CATCH AUTOGERATIDO E.PRINTSTACKTRACE (); }} System.out.print ("B"); deve_a = false; deve_b = false; deve_c = true; this.NotifyAll (); } public sincronizado void print_c () {while (deve_a || deve_b) {try {this.wait (); } catch (interruptedException e) {// TODO BLOCO DE CATCH AUTOGERATIDO E.PRINTSTACKTRACE (); }} System.out.print ("C"); deve_a = true; deve_b = false; deve_c = false; this.NotifyAll (); }}Mais uma vez, a importância da engenharia de software é comprovada; Em programas multithreaded, deve-se dizer que em programas, devemos colocar o código lógico de negócios na mesma classe para torná-lo altamente coeso e baixo acoplamento