public class DieLikeADog {
private static Object s = new Object();
private static int count = 0;
public static void main(String[] argv){
for(;;){
new Thread(new Runnable(){
public void run(){
synchronized(s){
count += 1;
System.err.println("New thread #"+count);
}
for(;;){
try {
Thread.sleep(1000);
} catch (Exception e){
System.err.println(e);
}
}
}
}).start();
}
}
}
在OS/X 10.5.6上的英特尔,和Java 6 5(见评论),这是我得到的
New thread #2547
New thread #2548
New thread #2549
Can't create thread: 5
New thread #2550
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:592)
at DieLikeADog.main(DieLikeADog.java:6)
class A extends Thread {
public void run() {
System.out.println("**************started***************");
for(double i = 0.0; i < 500000000000000000.0; i++) {
System.gc();
System.out.println(Thread.currentThread().getName());
}
System.out.println("************************finished********************************");
}
}
public class Manager {
public static void main(String[] args) {
for(double j = 0.0; j < 50000000000.0; j++) {
A a = new A();
a.start();
}
}
}
当我在我的2GB三星AMD处理器笔记本电脑上运行Trisquel linux (Ubuntu 18.04)研究这个主题时。它可以管理9534个线程,然后抛出特殊的异常
at java.base/java.lang.Thread.start0(Native Method)
at java.base/java.lang.Thread.start(Thread.java:803)
at Main.main(Main.java:11)
代码:
public class MultithreadingRunnable implements Runnable {
public void run() {
System.out.println("ThreadID " + Thread.currentThread().getId());
}
}
public class Main {
public static void main(String[] ars) {
for(int i = 0;i<10000;i++){
Thread mr = new Thread(new MultithreadingRunnable());
mr.start();
}
}
}