java多线程编程(2)交替输出数字和字母
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); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。