28.10.11

A Discussion about Semaphore, and Cyclic Barrier

Break the loop using threads (Threads forum at JavaRanch)

This is an interesting discussion involved Semaphore and Cyclic Barrier in Java. I just keep in here for further references.

Rohan Dhapodkar

  1. import java.util.concurrent.Semaphore;
  2. public class PrintUsingSemaphore {
  3. public static void main(String[] args) throws Exception{
  4. final Semaphore semaphore = new Semaphore(1);
  5. class MyPrinter implements Runnable {
  6. public void run(){
  7. for (int i = 0; i < 20; i++) {
  8. try {
  9. semaphore.acquire();
  10. System.out.println(i+" "+Thread.currentThread().getName());
  11. semaphore.release();
  12. Thread.sleep(100);
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }
  18. };
  19. for (int i = 0; i < 2; i++) {
  20. Thread t = new Thread(new MyPrinter());
  21. t.setPriority(Thread.MAX_PRIORITY-i*2);
  22. t.start();
  23. }
  24. Thread.sleep(100000);
  25. }
  26. }

  1. import java.util.concurrent.BrokenBarrierException;
  2. import java.util.concurrent.CyclicBarrier;
  3. public class PrintUsingCyclicBarrier {
  4. public static void main(String[] args) throws Exception{
  5. final CyclicBarrier semaphore = new CyclicBarrier(2,new Runnable() {
  6. public void run() {
  7. System.out.println();
  8. }
  9. });
  10. class MyPrinter implements Runnable {
  11. public void run(){
  12. for (int i = 0; i < 20; i++) {
  13. try {
  14. semaphore.await();
  15. System.out.print(i+" ");
  16. Thread.sleep(100);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }catch (BrokenBarrierException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. };
  25. for (int i = 0; i < 2; i++) {
  26. Thread t = new Thread(new MyPrinter());
  27. t.setPriority(Thread.MAX_PRIORITY-i*2);
  28. t.start();
  29. }
  30. Thread.sleep(100000);
  31. }
  32. }

Harsha Smith

  1. public static void main(String[] args) throws Exception{
  2. class MyPrinter implements Runnable {
  3. public void run(){
  4. for (int i = 0; i < 20; i++) {
  5. try {
  6. System.out.println(i +" "+Thread.currentThread().getName());
  7. TimeUnit.MILLISECONDS.sleep(1);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }
  13. };
  14. for (int i = 0; i < 2; i++) {
  15. Thread t = new Thread(new MyPrinter());
  16. t.start();
  17. }
  18. }