zoukankan      html  css  js  c++  java
  • 使用多线程计算阶乘累加 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;
        }
    }
    
    
    
    

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

  • 相关阅读:
    ecshop 调用指定分类的推荐,热卖,新品
    ecshop 首页调用指定类产品
    html常用笔记
    ecshop 修改flash图片大小
    ecshop 删除随机版权
    Java Web(一) Servlet详解!!
    Git使用总结
    git clone命令使用
    Lucene学习总结之四:Lucene索引过程分析
    Lucene学习总结之二:Lucene的总体架构
  • 原文地址:https://www.cnblogs.com/phyger/p/14029454.html
Copyright © 2011-2022 走看看