新建一个类,导入如下的测试代码:
1 public class TestNativeOutOfMemoryError { 2 public static void main(String[] args) { 3 4 for (int i = 0;; i++) { 5 System.out.println("i = " + i); 6 new Thread(new HoldThread()).start(); 7 } 8 } 9 10 } 11 12 class HoldThread extends Thread { 13 CountDownLatch cdl = new CountDownLatch(1); 14 15 public HoldThread() { 16 this.setDaemon(true); 17 } 18 19 public void run() { 20 try { 21 cdl.await(); 22 } catch (InterruptedException e) { 23 } 24 } 25 }
在我的开发环境上运行结果如下:
1 ...... 2 i = 3935 3 Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread 4 at java.lang.Thread.start0(Native Method) 5 at java.lang.Thread.start(Thread.java:714) 6 at com.study.thinking.in.java.concurrent.TestNativeOutOfMemoryError.main(TestNativeOutOfMemoryError.java:15)
每次运行结果并不完全一致,但是大差不差。
影响结果的几个参数:
1. 物理内存 使用64位OS能给虚拟机分配更大内存
2.JVMMemory 减少这项参数能增加并发的线程数,非倍数关系 -Xms1024m -Xmx1024m并不能比-Xms512m -Xmx512m多一倍的线程
3.ThreadStackSize 减少单个线程的栈大小,在有效范围内,是倍数关系
更多消息参考:http://sesame.iteye.com/blog/622670