标签:
一道经典的面试题目:两个线程,分别打印AB,其中线程A打印A,线程B打印B,各打印10次,使之出现ABABABABA.. 的效果
1 package com.shangshe.path; 2 3 public class ThreadAB { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 10 final Print business = new Print(); 11 12 new Thread(new Runnable() { 13 public void run() { 14 for(int i=0;i<10;i++) { 15 business.print_A(); 16 } 17 } 18 }).start(); 19 20 new Thread(new Runnable() { 21 public void run() { 22 for(int i=0;i<10;i++) { 23 business.print_B(); 24 } 25 } 26 }).start(); 27 28 } 29 } 30 class Print { 31 32 private boolean flag = true; 33 34 public synchronized void print_A () { 35 while(!flag) { 36 try { 37 this.wait(); 38 } catch (InterruptedException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } 42 } 43 System.out.print("A"); 44 flag = false; 45 this.notify(); 46 } 47 48 public synchronized void print_B () { 49 while(flag) { 50 try { 51 this.wait(); 52 } catch (InterruptedException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 } 56 } 57 System.out.print("B"); 58 flag = true; 59 this.notify(); 60 } 61 }
由上面的例子我们可以设计出3个线程乃至于n个线程的程序,下面给出的例子是3个线程,分别打印A,B,C 10次,使之出现ABCABC.. 的效果
1 public class ThreadABC { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 8 final Print business = new Print(); 9 10 new Thread(new Runnable() { 11 public void run() { 12 for(int i=0;i<100;i++) { 13 business.print_A(); 14 } 15 } 16 }).start(); 17 18 new Thread(new Runnable() { 19 public void run() { 20 for(int i=0;i<100;i++) { 21 business.print_B(); 22 } 23 } 24 }).start(); 25 26 new Thread(new Runnable() { 27 public void run() { 28 for(int i=0;i<100;i++) { 29 business.print_C(); 30 } 31 } 32 }).start(); 33 34 } 35 } 36 class Print { 37 38 private boolean should_a = true; 39 private boolean should_b = false; 40 private boolean should_c = false; 41 42 public synchronized void print_A () { 43 while(should_b || should_c) { 44 try { 45 this.wait(); 46 } catch (InterruptedException e) { 47 // TODO Auto-generated catch block 48 e.printStackTrace(); 49 } 50 } 51 System.out.print("A"); 52 should_a = false; 53 should_b = true; 54 should_c = false; 55 this.notifyAll(); 56 } 57 58 public synchronized void print_B () { 59 while(should_a || should_c) { 60 try { 61 this.wait(); 62 } catch (InterruptedException e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 } 66 } 67 System.out.print("B"); 68 should_a = false; 69 should_b = false; 70 should_c = true; 71 this.notifyAll(); 72 } 73 74 public synchronized void print_C () { 75 while(should_a || should_b) { 76 try { 77 this.wait(); 78 } catch (InterruptedException e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 } 82 } 83 System.out.print("C"); 84 should_a = true; 85 should_b = false; 86 should_c = false; 87 this.notifyAll(); 88 } 89 }
再一次证明了软件工程的重要性了;在多线程程序中,应该说在程序中,我们应该把那些业务逻辑代码放到同一个类中,使之高内聚,低耦合
标签:
原文地址:http://www.cnblogs.com/slming/p/5271129.html