Java多线程小测试

这是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求和,多线程将数据分为两个片段,采用两个线程分别求和。线程启动后在后台运行,代码继续向下扫描。

程序运行结果如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值