Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Problems;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- public class ReverseHello extends Thread {
- private ReentrantLock lock;
- private Condition cond;
- private static int howManyThreads=0;
- private static int whereToPrint = 49;
- private static int whereAmI = 49;
- private static CountDownLatch l = new CountDownLatch(50);
- public ReverseHello(ReentrantLock lock, Condition cond) {
- this.lock = lock;
- this.cond = cond;
- }
- public void run() {
- lock.lock();
- if(howManyThreads != 49) {
- ReverseHello s = new ReverseHello(lock,cond);
- howManyThreads++;
- lock.unlock();
- s.start();
- }
- l.countDown();
- try {
- l.await();
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- while(true) {
- lock.lock();
- if(!Thread.currentThread().getName().equals("Thread-"+whereToPrint)) {
- try {
- cond.await();
- }catch(Exception e) {}
- }else {
- System.out.println(Thread.currentThread().getName()+" ");
- whereToPrint--;
- cond.signalAll();
- lock.unlock();
- break;
- }
- }
- }
- public static void main(String[] args) {
- ReentrantLock lock = new ReentrantLock();
- Condition cond = lock.newCondition();
- ReverseHello s = new ReverseHello(lock,cond);
- s.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement