Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package threads;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- //kodi mushaobs shemdegnairad. or threads vaketeb, romelta nomrebia 0, 1
- //shemdeg orive threads vstartav, maq ragac counter romelic staticia da tavidan aris 0.
- //shemdeg sanam es counter 2 ar gaxdeba vzrdi, menole threads vabechdieb counteris luw mnishvnelobebs,
- //xolo meerte threads kent mnishvnelobebs. roca counter 2 gaxdeba vabreakeb threadebs.
- //ratomgac bolo thread yoveltvis daweitebuli rcheba.
- //52 xazze rac miweria is rom gavaketo mushaobs, agar rcheba daweitebuli magram ver vigeb ratom.
- //qvemot miweria ufro detalurad kitxva.
- public class EvenOdd extends Thread {
- private static int counter = 0;
- private ReentrantLock lock;
- private Condition cond;
- private int threadId;
- public EvenOdd(ReentrantLock lock, Condition cond,int threadId) {
- this.lock = lock;
- this.cond = cond;
- this.threadId = threadId;
- }
- @Override
- public void run() {
- while(true) {
- lock.lock();
- if(counter == 2) {
- System.out.println("Break thread numbered "+ threadId);
- lock.unlock();
- break;
- }
- if( counter % 2 == 0 ) {
- if(threadId == 0 ) {
- System.out.println("I am even thread numbered "+ threadId + " and i am printing number "+counter);
- counter++;
- cond.signalAll();
- }else {
- try {
- cond.await();
- } catch (InterruptedException e) { }
- }
- }else {
- if(threadId == 1 ) {
- System.out.println("I am odd thread numbered "+ threadId + " and i am printing number "+counter);
- counter++;
- cond.signalAll();
- }else {
- try {
- cond.await();
- } catch (InterruptedException e) { }
- }
- }
- // amas rom vwer, lock.unclok() - s, mushaobs, sworad. magram rom ar vwer bolo thread rcheba daweitebuli
- // verafrit ver vxvdebi ratom? sanam bolos wina thread damtavrdeba, anu sanam breaks gaaketebs mainc xom aketebs unlocks 22-e xazze
- // aq unlockis dawera ras cvlis?
- // lock.unlock();
- }
- }
- public static void main(String[] args) {
- ReentrantLock lock = new ReentrantLock();
- Condition cond = lock.newCondition();
- EvenOdd th1 = new EvenOdd(lock,cond,0); //even
- EvenOdd th2 = new EvenOdd(lock,cond,1); //odd
- th1.start();
- th2.start();
- }
- }
Add Comment
Please, Sign In to add comment