next up previous contents
Next: ThreadPool Up: Utility classes Previous: SlidingWindow

ReusableThread

Regular threads are usually created to execute a task and then die. Reusable threads can be assigned any number of tasks after they are done, so by reusing them, thread creation and destruction time (albeit small) is reduced. When a ReusableThread is created, it awaits its first task. A task has to be an object implementing interface Runnable. When a task is assigned (using method AssignTask), the task will be started (calling its run method) and the reusable thread waits until it is completed. When done, the reusable thread is ready to process another task, and so on, until it is killed. When a task is processed, no other task can be assigned, until the current task is finished. Calling AssignTask in this case results in an error message. An example of using reusable threads is shown below:

        ReusableThread t=new ReusableThread();
        t.Start();
        MyThread m1=new MyThread(1);
        MyThread m2=new MyThread(2);

        t.AssignTask(m1);
        t.WaitUntilDone();  // passive wait
        t.AssignTask(m2);
        t.WaitUntilDone();
        t.Stop();
Two threads (m1 and m2) are created (but not started) and assigned to the reusable thread in turn. The caller can use WaitUntilDone to wait for completion of a task.




1999-08-19