Error:
Exception in thread "Thread-2200" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Unknown Source)
at problem1.solvinging$solver.distancecalculator(Orienteering.java:107)
at problem1.solveing$solver.run(Orienteering.java:165)
班级:
public void distancecalculator(char [][]problem , int distancefound) {
Point p = new Point();
LinkedList<Point> q = new LinkedList<>();
q.add(origin);
int []x = {1,-1,0,0};
int []y = {0,0,1,-1};
dist[0][0] = distancefound;
while(!q.isEmpty()) {
p = q.getFirst();
for(int i = 0; i < 4; i++) {
int a = p.x + x[i];
int b = p.y + y[i];
if(a >= 0 && b >= 0 && a < m && b < n && dist[a][b]==2) {
dist[a][b] = 1 + dist[p.x][p.y] ;
if(k>0) {
solver s = new solver(newproblem,dist[a][b]);
new Thread(s).start();
}
我在执行程序时遇到上述错误,
但程序仍在运行。
我如何纠正它,请帮助我。
谢谢。如果需要,建议进行新的编辑
在您提供的代码中,没有位置可以从中删除元素LinkedList<Point> q
。该getFirst()
方法不会删除第一个元素。可能正因为如此,您创建了一个无限循环,因此每次运行都会创建一个新线程。
试试吧pollFirst()
。
问题注释后编辑
您可以使用java.util.concurrent包即Semaphore来限制线程数。在创建新线程之前,请在acquire
semapohre上调用mehotd。将semapohre
对象添加到solver
构造器,以便solver
完成后可以调用该release()
求解器对象中的方法。
尝试下面的代码,看它如何工作:
public class Main
{
public static void main(String args[])
{
new Main().run();
}
private void run()
{
Semaphore semaphore = new Semaphore(5, true);
for (int i = 0; i<6; i++)
{
try
{
semaphore.acquire(1);
new TestThread(i, semaphore).start();
}
catch (final InterruptedException e) {}
}
}
class TestThread extends Thread
{
private Semaphore semaphore;
private Integer id;
TestThread(final Integer id, final Semaphore semaphore)
{
this.semaphore = semaphore;
this.id = id;
}
@Override
public void run()
{
System.out.println("Thread " + id + " has started.");
try
{
Thread.sleep(5000);
}
catch (final InterruptedException e) {}
System.out.println("Thread " + id + " has stopped.");
semaphore.release(1);
}
}
}
有6个threads
需要被run
,但semaphore
只有5个在时间允许的。因此,第六必须等待。所有人threads
都只做一件事-等待5秒。因此,第六个thread
线程必须等待这5秒钟,以便其他线程之一可以完成,然后才能启动。
输出:
Thread 2 has started.
Thread 4 has started.
Thread 5 has started.
Thread 3 has started.
Thread 1 has started.
Thread 4 has stopped.
Thread 2 has stopped.
Thread 6 has started. //here the sixth thread has started - as soon as the other ones finished.
Thread 1 has stopped.
Thread 3 has stopped.
Thread 5 has stopped.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句