使用多线程计算阶乘累加 1!+2!+3!+...+19!+20!。其中一个线程计算阶乘,另一线程实现累加并输出结果。

运用多线程的信号灯法进行边加边计算!代码如下

public class JieChen {
    public static void main(String args[]){
        Sum sum = new Sum();
        new Play(sum).start();
        new Add(sum).start();

    }
}
class Play extends Thread{
    Sum sum;
    public Play(Sum sum){
        this.sum=sum;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            this.sum.s*=i;
            this.sum.count++;
            this.sum.play(sum.voe);
        }
    }
}
class Add extends Thread{
    Sum sum;
    public Add(Sum sum){
        this.sum=sum;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            sum.add();
            this.sum.sa+=this.sum.s;
        }
    }
}
class Sum{
    int s=1;
    int count=0;
    long sa=1;
    String voe;
    boolean flag = true;

    public synchronized void play(String voe){
        if(!flag){
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println("计算阶乘"+count+"!");
        this.notifyAll();
        this.voe=voe;
        this.flag=!this.flag;
    }
    public synchronized void add(){
        if(flag){
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println("加上阶乘结果为"+sa);
        this.notifyAll();
        this.flag=!this.flag;
    }
}



运行结果图
在这里插入图片描述

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Starbright.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值