Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static class WorkerThread extends Thread {
- private final ProgressBarHandler progressBarHandler;
- private final Semaphore[] semaphores;
- private final int index;
- private int progress;
- public WorkerThread(final ProgressBarHandler progressBarHandler, final Semaphore[] semaphores, final int index) {
- this.progressBarHandler = progressBarHandler;
- this.semaphores = semaphores;
- this.index = index;
- }
- /**
- * We use Semaphores here to coordinate the threads because the Semaphore in java is not 'fully-bracketed',
- * which means the thread to release a permit does not have to be the one that has acquired
- * the permit in the first place.
- * We can utilise this feature of Semaphore to let one thread to release a permit for the next thread.
- */
- @Override
- public void run() {
- final Semaphore currentSemaphore = semaphores[index];
- final Semaphore nextSemaphore = semaphores[(index + 1) % semaphores.length];
- try {
- while (true) {
- currentSemaphore.acquire();
- sleep(1000); // we use sleep call to mock some lengthy work.
- Message message = progressBarHandler.obtainMessage();
- message.arg1 = (progress += 10);
- progressBarHandler.sendMessage(message);
- nextSemaphore.release();
- if (progress == 100) {
- progress = 0;
- }
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement