• 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();

    }

    }

    }

    运行结果:

     

  • 相关阅读:
    Linux基础命令—网卡
    SHOW SLAVE STATUS解读
    perf工具crash的问题
    python学习之-requests模块基础
    DELL IDRAC API接口开发文档翻译及client模块
    cobbler ks文件解释--转载
    django学习之- 动态验证码学习
    django学习之- Ajax
    django学习之- modelForm
    django学习之- json序列化
  • 原文地址:https://www.cnblogs.com/linruier/p/9485224.html
Copyright © 2020-2023  润新知