Java multithreaded programming

Source: Internet
Author: User

Compare differences in running time (efficiency) between multithreaded programming and single-threaded programming in JAVA

Code:

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 ("Total added " +a.length+ " times " );

}

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 ("The time required for single-threaded calculation is " +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 ("The time required for double-threading calculation is " + (T4-T3));

}

catch (Exception e)

{

E.printstacktrace ();

}

}

}

Operation Result:

Java multithreaded programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.