mark一下,不停的看看notify和wait的没有理解
class Printer { int index=0; //输出奇数 public synchronized void printA(int a) { while(index%2==0) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } index++; System.out.println(a); notify(); } public synchronized void printB(char b) { while(index%2!=0) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } index++; System.out.println(b); notify(); } } public class 多线程1 { public static void main(String args[]) { Printer p=new Printer(); Thread t1=new Thread(new A(p)); Thread t2=new Thread(new B(p)); t1.start(); t2.start(); } } class A implements Runnable { Printer p=null; public A(Printer p) { this.p=p; } @Override public void run() { // TODO Auto-generated method stub for(int i=1;i<=26;i++) { p.printA(i); } } } class B implements Runnable { Printer p=null; public B(Printer p) { this.p=p; } public void run() { // TODO Auto-generated method stub for(char c=‘a‘;c<=‘z‘;c++) { p.printB(c); } } }
java多线程编程(2)交替输出数字和字母,布布扣,bubuko.com
原文:http://www.cnblogs.com/hansongjiang/p/3854171.html