Sebuah pertanyaan wawancara klasik: Dua utas, masing -masing mencetak AB, di antaranya cetak A, utas B cetak B, masing -masing mencetak 10 kali, sehingga efek dari Abababa ...
paket com.shangshe.path; Public Class Threadab { / ** * @param args * / public static void main (string [] args) {final cetak bisnis = new print (); utas baru (runnable baru () {public void run () {for (int i = 0; i <10; i ++) {Business.print_a ();}}}}). start (); utas baru (runnable baru () {public void run () {for (int i = 0; i <10; i ++) {Business.print_b ();}}}}). start (); }} kelas cetak {private boolean flag = true; public disinkronkan void print_a () {while (! flag) {coba {this.wait (); } catch (InterruptedException E) {// TODO Auto-Encanerated Catch Block E.PrintStackTrace (); }} System.out.print ("A"); bendera = false; this.notify (); } public disinkronkan void print_b () {while (flag) {coba {this.wait (); } catch (InterruptedException E) {// TODO Auto-Encanerated Catch Block E.PrintStackTrace (); }} System.out.print ("B"); bendera = true; this.notify (); }}Dari contoh di atas, kami dapat merancang program dengan 3 utas atau bahkan n utas. Contoh yang diberikan di bawah ini adalah 3 utas, masing -masing, A, B, dan C dicetak 10 kali, sehingga efek ABCABC ..
Public Class ThreadAbc { / ** * @param args * / public static void main (string [] args) {final print Business = new print (); utas baru (runnable baru () {public void run () {for (int i = 0; i <100; i ++) {Business.print_a ();}}}). start (); utas baru (runnable baru () {public void run () {for (int i = 0; i <100; i ++) {Business.print_b ();}}}). start (); utas baru (runnable baru () {public void run () {for (int i = 0; i <100; i ++) {Business.print_c ();}}}). start (); }} kelas cetak {private boolean seharusnya_a = true; private boolean seharusnya_b = false; private boolean seharusnya_c = false; public disinkronkan void print_a () {while (seharusnya_b || shoult_c) {coba {this.wait (); } catch (InterruptedException E) {// TODO Auto-Encanerated Catch Block E.PrintStackTrace (); }} System.out.print ("A"); harus_a = false; harus_b = true; harus_c = false; this.notifyall (); } public yang disinkronkan void print_b () {while (seharusnya_a || shouls_c) {coba {this.wait (); } catch (InterruptedException E) {// TODO Auto-Encanerated Catch Block E.PrintStackTrace (); }} System.out.print ("B"); harus_a = false; harus_b = false; harus_c = true; this.notifyall (); } public yang disinkronkan void print_c () {while (seharusnya_a || harus_b) {coba {this.wait (); } catch (InterruptedException E) {// TODO Auto-Encanerated Catch Block E.PrintStackTrace (); }} System.out.print ("C"); harus_a = true; harus_b = false; harus_c = false; this.notifyall (); }}Sekali lagi, pentingnya rekayasa perangkat lunak terbukti; Dalam program multi-threaded, harus dikatakan bahwa dalam program, kita harus memasukkan kode logika bisnis ke kelas yang sama untuk membuatnya sangat kohesif dan kopling rendah