轮流打印奇数偶数

class C{
    private volatile static int index=0;
    public synchronized void show(int a,boolean f) throws InterruptedException {
        for(;index<20;){
            if(index%2==0&&!f)
                wait();
            else if(index%2==1&&f)
                wait();
            else{
                System.out.println(a+"--->"+index);
                index++;
                notify();
            }
        }
    }
}

class D implements Runnable{
    private C c;
    private int a;
    private boolean f;

    public D(C c,int a,boolean f){
        this.c=c;
        this.a=a;
        this.f=f;
    }

    public void run(){
        try {
            c.show(a,f);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Main {

    public static void main(String[] args) {
        C c=new C();
        new Thread(new D(c,1,true)).start();
        new Thread(new D(c,2,false)).start();
    }
}

  


class C{
private volatile static int index=0;
public synchronized void show(int a,boolean f) throws InterruptedException {
for(;index<20;){
if(index%2==0&&!f)
wait();
else if(index%2==1&&f)
wait();
else{
System.out.println(a+"--->"+index);
index++;
notify();
}
}
}
}

class D implements Runnable{
private C c;
private int a;
private boolean f;

public D(C c,int a,boolean f){
this.c=c;
this.a=a;
this.f=f;
}

public void run(){
try {
c.show(a,f);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Main {

public static void main(String[] args) {
C c=new C();
new Thread(new D(c,1,true)).start();
new Thread(new D(c,2,false)).start();
}
}

猜你喜欢

转载自www.cnblogs.com/Xuxy1996/p/9651033.html
今日推荐