Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Downloader {
- private enum State {STARTED, STOPPED, PAUSED};
- private State mState = STOPPED;//initial state
- //...initialization and stuff
- private void synchronized getState() { return mState; }
- private void synchronized setState(State newState) { mState = newState; }
- private Thread workerThread = new Thread(new Runnable {
- @Override
- public void run() {
- //main loop for downloading, managed by states
- final int buffer_size = 8 * 1024;
- byte[] buffer = new byte[buffer_size];
- Task task = null;
- while( getState() != STOPPED)
- {
- while(getState() == PAUSED)
- {
- // this thread must be notified when awaken
- signal.wait();
- }
- if(getState() != STARTED) { continue; }
- while(task == null)
- {
- // this thread must be notified from outside
- // when new tasks is added to the work queue
- signal.wait();
- task = getNextTaskFromServer();
- }
- int bytesRead = task.input.read(buffer, buffer_size);
- if( -1 != bytesRead)
- {
- task.output.write(buffer,0, bytesRead);
- }
- else
- {
- task.close();
- task = null;
- }
- }
- Log.d("worker Thread is finished");
- }
- });
- public synchronized void start() {
- //check current state first
- assert(mState == STOPPED);
- mState = STARTED;
- workerThread.start();
- }
- public synchronized void stop() {
- mState = STOPPED;
- signal.NotifyAll();
- }
- public synchronized void pause() {
- assert(mState == STARTED);
- mState = PAUSED;
- }
- public synchronized void resume() {
- assert (mState == PAUSED);
- mState = STARTED;
- this.NotifyAll();
- }
- }
Add Comment
Please, Sign In to add comment