你的位置:首页 > 软件开发 > Java > Java多线程通信之两个线程分别打印AB各10次

Java多线程通信之两个线程分别打印AB各10次

发布时间:2016-03-13 03:00:08
一道经典的面试题目:两个线程,分别打印AB,其中线程A打印A,线程B打印B,各打印10次,使之出现ABABABABA.. 的效果 1 package com.shangshe.path; 2 3 public class ThreadAB { 4 5 /** 6 * ...

一道经典的面试题目:两个线程,分别打印AB,其中线程A打印A,线程B打印B,各打印10次,使之出现ABABABABA.. 的效果

Java多线程通信之两个线程分别打印AB各10次Java多线程通信之两个线程分别打印AB各10次
 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 block40         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 block54         e.printStackTrace();55       }56     }57     System.out.print("B");58     flag = true;59     this.notify();60   }61 }

原标题:Java多线程通信之两个线程分别打印AB各10次

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。