Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. package Problems;
  2.  
  3. import java.util.concurrent.CountDownLatch;
  4. import java.util.concurrent.locks.Condition;
  5. import java.util.concurrent.locks.ReentrantLock;
  6.  
  7. public class ReverseHello extends Thread {
  8.  
  9. private ReentrantLock lock;
  10. private Condition cond;
  11. private static int howManyThreads=0;
  12. private static int whereToPrint = 49;
  13. private static int whereAmI = 49;
  14. private static CountDownLatch l = new CountDownLatch(50);
  15. public ReverseHello(ReentrantLock lock, Condition cond) {
  16. this.lock = lock;
  17. this.cond = cond;
  18. }
  19. public void run() {
  20. lock.lock();
  21. if(howManyThreads != 49) {
  22. ReverseHello s = new ReverseHello(lock,cond);
  23. howManyThreads++;
  24. lock.unlock();
  25. s.start();
  26. }
  27.  
  28. l.countDown();
  29.  
  30. try {
  31. l.await();
  32. } catch (InterruptedException e1) {
  33. // TODO Auto-generated catch block
  34. e1.printStackTrace();
  35. }
  36.  
  37.  
  38. while(true) {
  39. lock.lock();
  40. if(!Thread.currentThread().getName().equals("Thread-"+whereToPrint)) {
  41. try {
  42. cond.await();
  43. }catch(Exception e) {}
  44. }else {
  45. System.out.println(Thread.currentThread().getName()+" ");
  46. whereToPrint--;
  47. cond.signalAll();
  48. lock.unlock();
  49. break;
  50. }
  51. }
  52.  
  53. }
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62. public static void main(String[] args) {
  63. ReentrantLock lock = new ReentrantLock();
  64. Condition cond = lock.newCondition();
  65.  
  66. ReverseHello s = new ReverseHello(lock,cond);
  67. s.start();
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement