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);

        }

        

        

    }

    

    

}