import java.util.*;
import java.util.Date;
class jisuanshijian
{
private int allsum=0,no1sum=0,no2sum=0;
private Random r=new Random();
private int n=r.nextInt(90)+10;
private int a[]=new int[n];
public jisuanshijian()
{
System.out.println("n="+n);
for (int i=0 ;i<n ;i++ ) {
a[i]=r.nextInt(1000);
}
}
public void qiusum()//单线程求和
{
int sum=0;
for (int i=0 ;i<n ;i++ ) {
System.out.println("a["+i+"]="+a[i]);
sum=sum+a[i];
}
System.out.println("sum="+sum);
}
public void firstone()//线程1求上半部份和
{
for (int i=0 ;i<n/2 ;i++ ) {
//System.out.println("a["+i+"]*="+a[i]);
no1sum=no1sum+a[i];
}
System.out.println("no1sum*="+no1sum);
}
public void secondone()//线程2求下半部分和
{
for (int i=n/2 ;i<n ;i++ ) {
//System.out.println("a["+i+"]**="+a[i]);
no2sum=no2sum+a[i];
}
System.out.println("no2sum**="+no2sum);
}
public void lastone()//当两个线程都完成后执行
{
allsum=no1sum+no2sum;
System.out.println("allsum="+allsum);
}
}
class xiancheng1 extends Thread
{
jisuanshijian data;
boolean b1=false;
public xiancheng1(jisuanshijian d)
{
data=d;
b1=true;
}
public void run()
{
data.firstone();
}
}
class xiancheng2 extends Thread
{
jisuanshijian data;
boolean b2=false;
public xiancheng2(jisuanshijian d)
{
data=d;
}
public void run()
{
data.secondone();
b2=true;
}
}
public class xiti84
{
public static void main(String[] args)
{
jisuanshijian cool=new jisuanshijian();
Date d1=new Date();
cool.qiusum();
Date d2=new Date();
long d=d2.getTime()-d1.getTime();
System.out.println("单线程:"+d+"Millisecond");
Date t1=new Date();
xiancheng1 bee=new xiancheng1(cool);
xiancheng2 nana=new xiancheng2(cool);
bee.start();
nana.start();
while (true) {
if (bee.b1 && nana.b2)
{
cool.lastone();
break;
}
}
Date t2=new Date();
long t=t2.getTime()-t1.getTime();
System.out.println("多线程使用时间"+t+"Millisecond");
}
}
代码有问题吗.请看看,测试和修改.