首页 > 代码库 > JAVA多线程编程
JAVA多线程编程
比较JAVA中多线程编程与单线程编程的运行时间(效率)的差异
代码:
package thread;
public class j extends Thread
{
private int a[];
j(int b[])
{
a=new int[b.length];
int len=b.length;
for(int i=0;i<len;i++)a[i]=b[i];
}
public void run()
{
int sum=0;
for(int i=0;i<a.length;i++)sum+=a[i];
System.out.println("一共相加了"+a.length+"次");
}
public static void main(String args[])
{
long t1=System.currentTimeMillis();
System.out.println(t1);
int n=0;
while(n<1000000)
{n=(int)(Math.random()*10000000);}
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=(int)Math.random()*100;
j j1=new j(a);
try
{
j1.start();
long t2=System.currentTimeMillis();
System.out.println(t2);
long t=t2-t1;
System.out.println("单线程计算所需时间是"+t);
}
catch(Exception e)
{
e.printStackTrace();
}
int b[]=new int[a.length/2];
for(int i=0;i<b.length;i++)b[i]=a[i];
int c[]=new int[a.length-b.length];
for(int i=0;i<c.length;i++)c[i]=a[b.length+i];
long t3=System.currentTimeMillis();
System.out.println(t3);
j j2=new j(b);j j3=new j(c);
try
{
j2.start();j3.start();
long t4=System.currentTimeMillis();
System.out.println(t4);
System.out.println("双线程计算所需时间是"+(t4-t3));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
运行结果:
JAVA多线程编程