多线程一定快吗?
1 /** 2 * 并发的意义,提高程序执行效率,但,少量或者简单的任务使用并发不一定执行的更快。 3 * </br>因为多线程CPU切换时间片(上下文)在一定数量级后会累加的很高。此时不如不用。 4 * </br>很奇怪的现象:第一次执行1亿次循环并发用时更慢,但是后面每次都更快一倍左右,甚至加到千亿循环也是。难道跟CPU平台有关? 5 * </br>单词:Concurrency 并发 serial 连续 6 */ 7 public class Concurrency { 8 /** 9 * 当访问到锁资源count时会切换上下文(CPU时间片) 10 */ 11 private static final long count = 100000000000L; 12 13 public static void main(String[] args) throws InterruptedException { 14 concurrency(); 15 serial(); 16 } 17 18 private static void concurrency() throws InterruptedException { 19 long start = System.currentTimeMillis(); 20 Thread thread = new Thread(new Runnable() { 21 22 @Override 23 public void run() { 24 long a = 0; 25 for (long i = 0; i < count; i++) { 26 a += 5; 27 } 28 } 29 30 }); 31 thread.start(); 32 long b = 0; 33 for (long i = 0; i < count; i++) { 34 b--; 35 } 36 thread.join();//作用是让run内的代码运行完毕,再运行接下来的代码。 37 long time = System.currentTimeMillis() - start; 38 System.out.println("concurrency :" + time + "ms,b=" + b); 39 } 40 41 private static void serial() { 42 long start = System.currentTimeMillis(); 43 long a = 0; 44 for (long i = 0; i < count; i++) { 45 a += 5; 46 } 47 long b = 0; 48 for (long i = 0; i < count; i++) { 49 b--; 50 } 51 long time = System.currentTimeMillis() - start; 52 System.out.println("serial :" + time + "ms,b=" + b + ",a=" + a); 53 } 54 55 }
最后问一下我注释内提到的现象,有人能知道问题所在吗?
浙公网安备 33010602011771号