一道經典的面試題目:兩個線程,分別打印AB,其中線程A打印A,線程B打印B,各打印10次,使之出現ABABABABA.. 的效果
package com.shangshe.path; public class ThreadAB { /** * @param args */ public static void main(String[] args) { final Print business = 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(); } } class Print { private boolean flag = true; public synchronized void print_A () { while(!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("A"); flag = false; this.notify(); } public synchronized void print_B () { while(flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("B"); flag = true; this.notify(); } }
由上面的例子我們可以設計出3個線程乃至於n個線程的程序,下面給出的例子是3個線程,分別打印A,B,C 10次,使之出現ABCABC.. 的效果
public class ThreadABC { /** * @param args */ public static void main(String[] args) { final Print business = 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(); } } class Print { private boolean should_a = true; private boolean should_b = false; private boolean should_c = false; public synchronized void print_A () { while(should_b || should_c) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("A"); should_a = false; should_b = true; should_c = false; this.notifyAll(); } public synchronized void print_B () { while(should_a || should_c) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("B"); should_a = false; should_b = false; should_c = true; this.notifyAll(); } public synchronized void print_C () { while(should_a || should_b) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("C"); should_a = true; should_b = false; should_c = false; this.notifyAll(); } }
再一次證明了軟體工程的重要性了;在多執行緒程式中,應該說在程式中,我們應該把那些業務邏輯程式碼放到同一個類別中,使之高內聚,低耦合
更多Java多執行緒實作同時輸出相關文章請關注PHP中文網!