定义⼀个线程A,输出1 〜 10之间的整数, 定义⼀个线程B,逆序输出1 〜 10之间的整数,要求线程A和线程B交替输出。

方法一:

public class Print {
    boolean flag=true;
    public synchronized void printA(int i){
        if(flag==false){
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        } System.out.print(i+",");
        flag=false;
        notify();
    }
    public  synchronized void printB(int i){
        if(flag==true){
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        }System.out.print(i+",");
        flag=true;
        notify();
    }
}
class A extends Thread{
    private  Print p;
    public A(Print p){
        this.p=p;
    }
    @Override
    public void run(){
        for(int i=1;i<=10;i++){
            p.printA(i);
        }
    }

}
class B extends Thread{
    private Print p;
    public B(Print p){
        this.p=p;
    }
    @Override
    public void run(){
        for(int i=10;i>=1;i--){
            p.printB(i);
        }
    }

}

public class dsd {
    public static void main(String args[]){

        Print p=new Print();
        A a=new A(p);
        B b=new B(p);
        a.start();
        b.start();
    }

}


方法二:

public class Work6 {
    public static void main(String[] args) {
        Object obj = new Object();

        A a = new A(obj);
        B b = new B(obj);

        a.start();
        b.start();
    }
}

class A extends Thread {
    Object obj;

    public A(Object obj) {
        super();
        this.obj = obj;
    }

    //正序打印
    @Override
    public void run() {
        synchronized (obj) {
            for (int i = 1; i <= 10; i++) {
                System.out.print(i + ",");
                obj.notify();
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class B extends Thread {
    Object obj;

    public B(Object obj) {
        super();
        this.obj = obj;
    }

    //逆序打印
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (obj) {
            for (int i = 10; i > 0; i--) {
                System.out.print(i + ",");
   obj.notify();
                if (i > 0) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值