python123阶乘累加_使用多线程计算阶乘累加 1!+2!+3!+...+19!+20!。其中一个线程计算阶乘,另一线程实现累加并输出结果。...
運(yùn)用多線程的信號(hào)燈法進(jìn)行邊加邊計(jì)算!代碼如下
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("計(jì)算階乘"+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("加上階乘結(jié)果為"+sa);
this.notifyAll();
this.flag=!this.flag;
}
}
運(yùn)行結(jié)果圖
總結(jié)
以上是生活随笔為你收集整理的python123阶乘累加_使用多线程计算阶乘累加 1!+2!+3!+...+19!+20!。其中一个线程计算阶乘,另一线程实现累加并输出结果。...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4299元起 荣耀70 Pro+手机发布
- 下一篇: python全套学习方法_python学