Multi-threaded download has a long history, such as FlashGet, netants and other tools, they are lazy in the HTTP protocol support (range field specify the request content range), first read out the request content (that is, to download the file) size, divided into a number of blocks, The chunks are distributed to each thread to download, the thread downloads data from the beginning of the paragraph, and at the end of the paragraph, the content downloaded by multiple threads is eventually written to the same file.
Study only useful, job requirements: Assign multiple tasks to multiple threads to execute, and there will be a task list assigned to threading strategy thinking: Known: 1. A list of tasks to be performed, 2. Specifies the number of threads to start; The problem is what each thread actually performs.
The strategy is that the task list is divided into consecutive threads, ensuring that the average number of tasks per thread can be allocated, and that the remaining tasks are appended to the thread in turn from the previous to the first-just the number, the actual tasks performed by each thread are continuous. If there are more monks (threads) of porridge (Task) less, the actual number of threads to start is equal to the number of tasks, one pick. Here only to achieve each thread sweep their own front of the snow, the action quickly completed after seeing other threads tired are helpless.
Implementation and presentation code is as follows: implemented by three classes, written in a Java file: Taskdistributor for Task Dispatcher, task for tasks to be performed, workthread worker threads. The code uses the command pattern, if can match with the listener, uses the observer pattern to control the UI display to be even more wonderful, can realize like downloading the block coloring jumps the movement, here defines the next point of view.
There are more detailed comments in the code, and it's easy to understand the comments and the execution results. Main () is the test method