고전적인 인터뷰 질문 : 두 개의 스레드는 각각 AB를 인쇄하는데, 그 중에도 스레드 A, 스레드 B 인쇄 B가 각각 10 배 인쇄하여 Abababa의 효과가 있습니다 ...
패키지 com.shangshe.path; Public Class Threadab { / ** * @param args * / public static void main (String [] args) {Final Print Business = New Print (); 새 스레드 (new runnable () {public void run () {for (int i = 0; i <10; i ++) {business.print_a ();}}}}); start (); 새 스레드 (new runnable () {public void run () {for (int i = 0; i <10; i ++) {business.print_b ();}}}}); start (); }} class print {private boolean flag = true; public synchronized void print_a () {while (! flag) {try {this.wait (); } catch (InterruptedException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} system.out.print ( "a"); flag = false; this.notify (); } public synchronized void print_b () {while (flag) {try {this.wait (); } catch (InterruptedException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} system.out.print ( "b"); flag = true; this.notify (); }}위의 예에서 3 개의 스레드 또는 N 스레드가있는 프로그램을 설계 할 수 있습니다. 아래에 주어진 예제는 각각 3 개의 스레드, A, B 및 C는 ABCABC의 효과를 10 번 인쇄합니다.
public class threadabc { / ** * @param args * / public static void main (String [] args) {최종 인쇄 비즈니스 = new print (); 새 스레드 (new runnable () {public void run () {for (int i = 0; i <100; i ++) {business.print_a ();}}). start (); 새 스레드 (new runnable () {public void run () {for (int i = 0; i <100; i ++) {business.print_b ();}}}). start (); 새 스레드 (new runnable () {public void run () {for (int i = 0; i <100; i ++) {business.print_c ();}}}). start (); }} class print {private boolean dourd_a = true; 개인 부울 DOTH_B = FALSE; 개인 부울 DOSPL_C = FALSE; public synchronized void print_a () {while (while_b || should_c) {try {this.wait (); } catch (InterruptedException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} system.out.print ( "a"); hourd_a = false; hourd_b = true; whit_c = 거짓; this.notifyall (); } public synchronized void print_b () {while (while_a || should_c) {try {this.wait (); } catch (InterruptedException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} system.out.print ( "b"); hourd_a = false; hourd_b = false; duber_c = true; this.notifyall (); } public synchronized void print_c () {while (while_a || should_b) {try {this.wait (); } catch (InterruptedException e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} system.out.print ( "C"); hourd_a = true; hourd_b = false; whit_c = 거짓; this.notifyall (); }}다시 한번, 소프트웨어 엔지니어링의 중요성이 입증되었습니다. 멀티 스레드 프로그램에서 프로그램에서는 비즈니스 로직 코드를 동일한 클래스에 넣어 고도로 응집력이 있고 낮은 커플 링을 만들어야한다고 말해야합니다.