这是thread_test.java
public class thread_test extends Thread {
public int start , end;
public static int ans = 0 ;
public thread_test(int _start, int _end)
{
start = _start;
end = _end;
}
//重写run()方法;
public void run()
{
int count = 0 ;
for ( int i = start ; i <= end ; ++i)
count += i ;
ans += count;
}
}
这是test.java
public class test {
public static void main(String args[])
{
System.out.println("单线程:");
long time1 = (long) System.nanoTime();
thread_test t = new thread_test(1,10000);
t.start();
while(t.isAlive());
long time2 = (long) System.nanoTime();
System.out.println(t.ans);
System.out.println("总耗时:"+ (time2 - time1)+"ns");
t.ans = 0;
System.out.println("\n多线程:");
long time3 = (long) System.nanoTime();
thread_test t1 = new thread_test(1,5000);
thread_test t2 = new thread_test(5001,10000);
t1.start();
t2.start();
//当t1和t2都运行完毕才跳出循环输出ans;
while (t1.isAlive() || t2.isAlive());
long time4 = (long) System.nanoTime();
System.out.println(t1.ans);
System.out.println("总耗时:"+ (time4 - time3)+"ns");
}
}
程序实现1到10000求和,多线程将数据分为两个片段,采用两个线程分别求和。线程启动后在后台运行,代码继续向下扫描。
程序运行结果如下: