views:

77

answers:

2

Hi, 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.

A: 

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
yes, i call the seven threads one by one in Invokelater().
Farhan
+3  A: 

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
Thanks Sir i try it.
Farhan