线程多不一定快,如下:
package www.demo.xctester; public class xcTester { private static final long count=1000; public static void main(String[] args) throws InterruptedException { concurrency(); serial(); } private static void concurrency() throws InterruptedException { long start = System.currentTimeMillis(); //通过匿名内部类来创建线程 Thread thread = new Thread(new Runnable() { public void run() { int a = 0; for (long i = 0; i < count; i++) { a += 5; } } }); thread.start(); //并行执行 int b = 0; for (int i = 0; i < count; i++) { b--; } thread.join();//等待线程结束 long time = System.currentTimeMillis() - start; System.out.print(time + "ms"); } private static void serial(){ long start = System.currentTimeMillis(); int a = 0; for (int i = 0; i < count; i++) { a += 5; } //串行执行 int b = 0; for (int i = 0; i < count; i++) { b--; } long time = System.currentTimeMillis() - start; System.out.print(time + "ms"); } }
以下是我测试的结果:
循环次数 |
串行执行耗时/ms |
并行执行耗时/ms |
并发比串行快多少 |
1千次 |
0 |
1 |
慢 |
1万次 |
0 |
1 |
慢 |
十万次 |
2 |
2 |
差不多 |
一百万次 |
4 |
4 |
差不多 |
一千万次 |
13 |
9 |
快 |
一亿次 |
104 |
55 |
快 |
如何让10个线程按照顺序打印0123456789?
package www.demo.xcstest; public class xcsTest { private static final int endNum = 10; static int orderNum = 0; //公正锁,只有获得该锁资源才能进行下一步 static Object object = new Object(); static class threadxcsTest extends Thread{ private int printNum; public threadxcsTest(int printNum){ this.printNum = printNum;//获取自己需要打印的数字 } @Override public void run(){ synchronized (object) {//判断该资源是否正在被使用 while (orderNum < endNum) {//如果资源空闲则锁定资源判断是否已经打印完成 if(orderNum == printNum){//没有打印完成则判断是否是自己需要打印的数字 System.out.print(printNum); orderNum++; if(orderNum == 10){ System.out.println("打印完成!"); } object.notifyAll();//打印完成后唤醒所有等待的线程 }else{ try { object.wait();//不是自己打印的数字则该线程被阻塞,继续等待 } catch (Exception e) { System.out.println("线程" + printNum + "打断了!"); e.printStackTrace(); } } } } } } public static void main(String[] args) { threadxcsTest[] tests = new threadxcsTest[10]; //初始化线程并启动 //为了证明线程锁的作用,线程从后面启动 for (int i = endNum - 1; i >= 0 ; i--) { tests[i] = new threadxcsTest(i); tests[i].start(); } } }
以上代码均已经过测试