完成一个简单的任务:让代码分别针对 a 和 b 两个整数,自增100亿次。
比较串行和并发执行哪个效率更高。
并发执行 相对于 串行 时间节约 44% 左右。
并没有有的人一开始想的 50%,是因为线程的创建和销毁以及线程的调度都是有开销的。
public class ThreadDemo2 {
private static long count = 100_0000_0000L;
public static void main(String[] args) {
concurrency(); // 并发执行自增
// serial(); // 串型自增
}
// 多线程并发自增
private static void concurrency() {
long begin = System.currentTimeMillis(); // 单位是 ms
// 创建了一个匿名内部类。这个类继承自Thread。{}中就可以写这个子类的具体逻辑了。
Thread thread1 = new Thread() {
@Override
public void run() {
int a = 0;
for (long i = 0; i < count; i++) {
a++;
}
}
};
// 启动线程必须要调用 start 方法。
thread1.start();
Thread thread2 = new Thread() {
@Override
public void run() {
int b = 0;
for (long i = 0; i < count; i++) {
b++;
}
}
};
thread2.start();
try {
// 线程等待的逻辑
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis(); // 单位是 ms
System.out.println("time: "+(end-begin)+"ms");
// 结果大概为 :15.2 s;
}
// 串型自增
private static void serial() {
// 如何衡量一段代码的执行时间?
// 代码开始的时候执行的时候记录一个时间节点。
// 代码结束执行的时候,再记录一个时间节点。
// 两者相减就是这个代码的执行时间。
long begin = System.currentTimeMillis(); // 单位是 ms
int a = 0;
for (long i = 0; i < count; i++) {
a++;
}
int b = 0;
for (long i = 0; i < count; i++) {
b++;
}
long end = System.currentTimeMillis(); // 单位是 ms
System.out.println("time: "+(end-begin)+"ms");
// 大概是 27 s;
}
}
每个人执行的结果有略微不同,但是大致相似。