Eine klassische Interviewfrage: Zwei Threads drucken AB, darunter Thread A Drucke A, Thread B Drucke B, druckt jeweils jeweils 10 Mal, so dass die Wirkung von Abababa ...
Paket com.shangshe.path; public class Threadab { / ** * @param args * / public static void main (String [] args) {Final Print Business = new print (); neuer Thread (new Runnable () {public void run () {für (int i = 0; i <10; i ++) {business.print_a ();}}}}). start (); neuer Thread (new Runnable () {public void run () {für (int i = 0; i <10; i ++) {business.print_b ();}}}}). start (); }} Klasse Print {private boolean flag = true; public synchronisierte void print_a () {while (! flag) {try {this.wait (); } catch (InterruptedException e) {// Todo automatisch generierter Catch-Block e.printstacktrace (); }} System.out.print ("a"); Flag = Falsch; this.notify (); } public synchronisierte void print_b () {while (flag) {try {this.wait (); } catch (InterruptedException e) {// Todo automatisch generierter Catch-Block e.printstacktrace (); }} System.out.print ("b"); Flag = wahr; this.notify (); }}Aus dem obigen Beispiel können wir ein Programm mit 3 Threads oder sogar N -Threads entwerfen. Das nachstehend angegebene Beispiel ist 3 Threads, a, b und c, werden zehnmal gedruckt, so dass die Wirkung von ABCABC ..
public class threadabc { / ** * @param args * / public static void main (String [] args) {Final Print Business = new print (); neuer Thread (new Runnable () {public void run () {für (int i = 0; i <100; i ++) {business.print_a ();}}}). start (); neuer Thread (new Runnable () {public void run () {für (int i = 0; i <100; i ++) {business.print_b ();}}}). start (); neuer Thread (new Runnable () {public void run () {für (int i = 0; i <100; i ++) {business.print_c ();}}}). start (); }} Klasse print {private boolean sollte_a = true; privat boolean sollte_b = false; private boolean sollte_c = false; public synchronisierte void print_a () {while (sollte_b || sollte_c) {try {this.wait (); } catch (InterruptedException e) {// Todo automatisch generierter Catch-Block e.printstacktrace (); }} System.out.print ("a"); sollte_a = false; sollte_b = true; sollte_c = false; this.notifyall (); } public synchronisierte void print_b () {while (sollte_a || sollte_c) {try {this.wait (); } catch (InterruptedException e) {// Todo automatisch generierter Catch-Block e.printstacktrace (); }} System.out.print ("b"); sollte_a = false; sollte_b = false; sollte_c = true; this.notifyall (); } public synchronisierte void print_c () {while (sollte_a || sollte_b) {try {this.wait (); } catch (InterruptedException e) {// Todo automatisch generierter Catch-Block e.printstacktrace (); }} System.out.print ("c"); sollte_a = true; sollte_b = false; sollte_c = false; this.notifyall (); }}Wiederum wird die Bedeutung des Software -Engineering bewiesen. In Multi-Thread-Programmen sollte gesagt werden, dass wir in Programmen den Geschäftslogikcode in dieselbe Klasse einsetzen sollten, um ihn sehr kohärent und niedrig zu koppeln