TOO MANY THREADS ERROR EXCEPTION

岁酱吖の 提交于 2019-12-23 20:33:23

问题


i am facing a problem while making an application of Blackberry that i have upto 7 threds call, of which each downloads an audio from the Server and it works fine but when i start my application twice then an uncaught exception has been occurred that "TOO MANY THREADS ERROR EXCEPTION", So, let me know that how i can solve this problem.


回答1:


i think instead of starting 7 threads use single thread. 1. create a TaskWorker class

public class TaskWorker implements Runnable {
    private boolean quit = false;
    private Vector queue = new Vector();

    public TaskWorker() {
        new Thread(this).start();
    }

    private Task getNext() {
        Task task = null;
        if (!queue.isEmpty()) {
            task = (Task) queue.firstElement();
        }
        return task;
    }

    public void run() {
        while (!quit) {
            Task task = getNext();
            if (task != null) {
                task.doTask();
                queue.removeElementAt(task);
            } else {// task is null and only reason will be that vector has no more tasks
                synchronized (queue) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

     public void addTask(Task task) {
        synchronized (queue) {
            if (!quit) {
                queue.addElement(task);
                queue.notify();

            }

        }
    }

    public void quit() {
        synchronized (queue) {
            quit = true;
            queue.notify();
        }
    }
}

2. create a abstract Task class

public abstract class Task {

    abstract void doTask();
}

3. now create task.

public class DownloadTask extends Task{

        void doTask() {

            //do something
        }

    }

4. and add this task to the taskworker thread

TaskWorker taskWorker = new TaskWorker();
                    taskWorker.addTask(new DownloadTask());



回答2:


If it happens when you RESTART the application, it means you must have some zombies... are you sure to join all your threads ?



来源:https://stackoverflow.com/questions/3394560/too-many-threads-error-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!