Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. private static class WorkerThread extends Thread {
  2.  
  3. private final ProgressBarHandler progressBarHandler;
  4. private final Semaphore[] semaphores;
  5. private final int index;
  6. private int progress;
  7.  
  8. public WorkerThread(final ProgressBarHandler progressBarHandler, final Semaphore[] semaphores, final int index) {
  9. this.progressBarHandler = progressBarHandler;
  10. this.semaphores = semaphores;
  11. this.index = index;
  12. }
  13.  
  14. /**
  15. * We use Semaphores here to coordinate the threads because the Semaphore in java is not 'fully-bracketed',
  16. * which means the thread to release a permit does not have to be the one that has acquired
  17. * the permit in the first place.
  18. * We can utilise this feature of Semaphore to let one thread to release a permit for the next thread.
  19. */
  20. @Override
  21. public void run() {
  22. final Semaphore currentSemaphore = semaphores[index];
  23. final Semaphore nextSemaphore = semaphores[(index + 1) % semaphores.length];
  24.  
  25. try {
  26. while (true) {
  27. currentSemaphore.acquire();
  28.  
  29. sleep(1000); // we use sleep call to mock some lengthy work.
  30. Message message = progressBarHandler.obtainMessage();
  31. message.arg1 = (progress += 10);
  32. progressBarHandler.sendMessage(message);
  33.  
  34. nextSemaphore.release();
  35.  
  36. if (progress == 100) {
  37. progress = 0;
  38. }
  39. }
  40.  
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement