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);
} } }
上一篇:命令行添加删除tomcat服务


下一篇:Python 中 Iterator(迭代器)和Iterable(迭代对象)的区别