养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

多线程解杨辉三角

时间:2024-11-11 18:03:21

用java多线程解决杨辉三角问题

工具/原料

eclipse

jdk1.7

方法/步骤

1、创建基本对象,实现runnable接口

2、算法:两个静态数组初始化一个数组(赋值)取得两个元素加和存入新数组对应位置中新数组头尾增添新数组覆盖原数组继续迭代

3、代码如下:packageleo.mythread;importjav瞢铍库祢a.util.*;impor墉掠载牿tjava.util.concurrent.*;publicclassMySequenceimplementsRunnable{publicintleftindex;privateCountDownLatchdoneSignal;publicstaticint[]oarray;publicstaticint[]narray;publicintround;publicMySequence(CountDownLatchdoneSignal,intleftindex){this.doneSignal=doneSignal;this.leftindex=leftindex;}publicstaticintcounting(intleft,intright){returnleft+right;}publicvoidspush(intnumber,intindex){synchronized(narray){narray[index+1]=number;System.out.println(number);System.out.println("index:"+(index+1)+""+narray[index+1]);}}publicintsget(intindex){synchronized(oarray){returnoarray[index];}}@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubintl=0;intr=0;ints=0;l=this.sget(this.leftindex);r=this.sget(this.leftindex+1);s=counting(l,r);this.spush(s,this.leftindex);doneSignal.countDown();}}

4、publicvoidtestt筠续师诈ri()throwsInterruptedException{MySequence.oa鸡堕樱陨rray=newint[2];MySequence.oarray[0]=1;MySequence.oarray[1]=1;for(inti=0;i<10;i++){CountDownLatchdoneSignal=newCountDownLatch(i+1);MySequence.narray=newint[i+3];MySequence.narray[0]=1;Thread[]p=newThread[i+1];for(intj=0;j<i+1;j++){p[j]=newThread(newMySequence(doneSignal,j));p[j].start();}doneSignal.await();MySequence.narray[i+2]=1;for(intk=0;k<MySequence.narray.length;k++){System.out.println(MySequence.narray[k]);}MySequence.oarray=MySequence.narray;}}

© 一点知识