创建3个线程为Thread1Thread2Thread3 需要对一个数字进行递减操作 当数字递减到0的时候,输出“数字为0,结束递减”

多线程,对run方法内部进行一个同步运算。

以下是代码:

package 一般测试题;

public class 依次打印递增数字 {
    /**
     * 创建三个线程进行分段叠加
     * 每个线程叠加四次
     *
     */
    public static void main(String[] args) {
        new Thread(new Add(1)).start();
        new Thread(new Add(2)).start();
        new Thread(new Add(3)).start();

    }
}
class Add implements Runnable{
    //定义一个线程ID
    private int threadID;
    //需要进行叠加的数字
    private static int printNum = 9;
    //构造方法获取thread的ID
    public Add(int threadID){
        this.threadID = threadID;
    }
    @Override
    public void run() {
        while (printNum  >=0){
            synchronized (Add.class){
                System.out.println("当前的线程是:"+"---->"+threadID+"线程");
               int index = (printNum%3+1);//计算当前线程的数是和要对其操作的数来求得对应
                if(index == threadID){
                        System.out.println("线程"+threadID+":"+(printNum--));
                        if (printNum<0){
                            System.out.println("为0结束!");
                        }
                    Add.class.notifyAll();
                }else {
                    try {
                       Add.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}

如果想用三个线性,依次的去输出a b c的话,可以试试以下的方式:

package 一般测试题;

public class 依次打印递增数字 {
    /**
     * 创建三个线程进行分段叠加
     * 每个线程叠加四次
     *
     */
    public static void main(String[] args) {
        new Thread(new Add(1)).start();
        new Thread(new Add(2)).start();
        new Thread(new Add(3)).start();

    }
}
class Add implements Runnable{
    //定义一个线程ID
    private int threadID;
    //需要进行叠加的数字
    private static int printNum = 9;
    String[] a={"a","c","b"};
    //构造方法获取thread的ID
    public Add(int threadID){
        this.threadID = threadID;
    }
    @Override
    public void run() {
        while (printNum  >=0){
            synchronized (Add.class){
                System.out.println("当前的线程是:"+"---->"+threadID+"线程");
               int index = (printNum%3+1);//计算当前线程的数是和要对其操作的数来求得对应
                if(index == threadID){
                        System.out.println("线程"+threadID+":"+(printNum--)+a[index-1]);
                        if (printNum<0){
                            System.out.println("为0结束!");
                        }
                    Add.class.notifyAll();
                }else {
                    try {
                       Add.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值