码迷,mamicode.com
首页 > 其他好文 > 详细

轮流打印奇数偶数

时间:2018-09-15 16:37:29      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:try   偶数   打印   amp   style   color   ==   runnable   exce   

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

轮流打印奇数偶数

标签:try   偶数   打印   amp   style   color   ==   runnable   exce   

原文地址:https://www.cnblogs.com/Xuxy1996/p/9651033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!