3

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.

Brian Willis
  • 22,768
  • 9
  • 46
  • 50
Muhammad Farhan Habib
  • 1,859
  • 20
  • 23
  • Notice how no other questions here have their title all in caps? Why did you choose to be different? –  Aug 03 '10 at 07:53

2 Answers2

5

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());
Vivart
  • 14,900
  • 6
  • 36
  • 74
1

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

Guillaume Lebourgeois
  • 3,796
  • 1
  • 20
  • 23