Guest User

Untitled

a guest
Jul 17th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. package threads;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.ReentrantLock;
  4.  
  5. //kodi mushaobs shemdegnairad. or threads vaketeb, romelta nomrebia 0, 1
  6. //shemdeg orive threads vstartav, maq ragac counter romelic staticia da tavidan aris 0.
  7. //shemdeg sanam es counter 2 ar gaxdeba vzrdi, menole threads vabechdieb counteris luw mnishvnelobebs,
  8. //xolo meerte threads kent mnishvnelobebs. roca counter 2 gaxdeba vabreakeb threadebs.
  9. //ratomgac bolo thread yoveltvis daweitebuli rcheba.
  10. //52 xazze rac miweria is rom gavaketo mushaobs, agar rcheba daweitebuli magram ver vigeb ratom.
  11. //qvemot miweria ufro detalurad kitxva.
  12.  
  13. public class EvenOdd extends Thread {
  14.  
  15. private static int counter = 0;
  16. private ReentrantLock lock;
  17. private Condition cond;
  18. private int threadId;
  19. public EvenOdd(ReentrantLock lock, Condition cond,int threadId) {
  20. this.lock = lock;
  21. this.cond = cond;
  22. this.threadId = threadId;
  23. }
  24.  
  25. @Override
  26. public void run() {
  27. while(true) {
  28. lock.lock();
  29. if(counter == 2) {
  30. System.out.println("Break thread numbered "+ threadId);
  31. lock.unlock();
  32. break;
  33. }
  34. if( counter % 2 == 0 ) {
  35. if(threadId == 0 ) {
  36. System.out.println("I am even thread numbered "+ threadId + " and i am printing number "+counter);
  37. counter++;
  38. cond.signalAll();
  39. }else {
  40. try {
  41. cond.await();
  42. } catch (InterruptedException e) { }
  43. }
  44. }else {
  45. if(threadId == 1 ) {
  46. System.out.println("I am odd thread numbered "+ threadId + " and i am printing number "+counter);
  47. counter++;
  48. cond.signalAll();
  49. }else {
  50. try {
  51. cond.await();
  52. } catch (InterruptedException e) { }
  53. }
  54. }
  55. // amas rom vwer, lock.unclok() - s, mushaobs, sworad. magram rom ar vwer bolo thread rcheba daweitebuli
  56. // verafrit ver vxvdebi ratom? sanam bolos wina thread damtavrdeba, anu sanam breaks gaaketebs mainc xom aketebs unlocks 22-e xazze
  57. // aq unlockis dawera ras cvlis?
  58.  
  59. // lock.unlock();
  60. }
  61. }
  62.  
  63. public static void main(String[] args) {
  64. ReentrantLock lock = new ReentrantLock();
  65. Condition cond = lock.newCondition();
  66. EvenOdd th1 = new EvenOdd(lock,cond,0); //even
  67. EvenOdd th2 = new EvenOdd(lock,cond,1); //odd
  68. th1.start();
  69. th2.start();
  70. }
  71. }
Add Comment
Please, Sign In to add comment