我创建了两个线程。在run()
方法内部,在while循环下运行线程的睡眠时间为1000ms。当我运行此程序时,一段时间后,出现错误:
无法创建新的本机线程
我的代码:(已更新)
class MainClass{
RunThread t1 = new RunThread("read_thread");
t1.start();
RunThread t2 = new RunThread("write_thread");
t2.start();
System.out.println(Thread.activeCount());
}
class RunThread implements Runnable{
Thread t;
String threadName;
public RunThread(String name){
threadName=name;
}
public void start(){
if(t==null)
t = new Thread(this,threadName);
t.start();
}
public void run() {
while (true) {
if(threadName.equalsIgnoreCase("read_thread")){
//do something
System.out.println(Thread.activeCount());
Thread.sleep(1000);
}
if (threadName.equalsIgnoreCase("write_thread")) {
//do something
System.out.println(Thread.activeCount());
Thread.sleep(500);
}
}
答案 0 :(得分:1)
您的start()方法创建一个新的Thread对象,并递归(无限期地)调用自己。
创建线程对象有效地创建了documentation中所述的操作系统级别的新线程。
因此之一:
a)系统无法分配更多内存来实例化那些线程或
b)您的操作系统可以处理的线程数已达到极限。