Keerthana Raj
Keerthana Raj

Reputation: 3

Working of Await and signal in concurrent Java

I am a beginner and I have to write a code for particular prob stmt. I wanna use locks to implement it. Beforehand, I gotto know the working of locks and its methods.

In my below code, I need the first thread to await and second thread to signal the first thread and wake up. But the signal is not waking up my waiting thread. Could anyone pls help.

package com.java.ThreadDemo;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadEx {

    public static void main (String args[]) throws InterruptedException
    {
        ThreadMy mt[]=new ThreadMy[6];
        int a=1, b=2;
        mt[1] = new ThreadMy(a);
        mt[2] = new ThreadMy(b);
        mt[1].start ();
        Thread.sleep(100);
        mt[2].start ();
    }   
}
class ThreadMy extends Thread
{
    final ReentrantLock  rl = new ReentrantLock() ;
    Condition rCond = rl.newCondition();
    //private final Condition wCond = rl.newCondition();

    int i;
    int c;

    public ThreadMy(int a)
    {
        c=a;
    }

    public void run() 
    {
        System.out.print("\nThread "+c+" "+rl.isHeldByCurrentThread()+" "+rl.isLocked() );
        rl.lock();
    try
    {
    //for (i=0;i<2;i++)

    System.out.print("\nThread "+c+" "+rl.isHeldByCurrentThread()+" "+rl.getHoldCount() );
    try
    {
        if (c==1)
        {       
            System.out.print("await\n");
            rCond.await();
            //rCond.await(200, TimeUnit.MILLISECONDS);

            System.out.print("signal\n");
        }
        else
        {
            System.out.print("P");
            rCond.signal();
            Thread.sleep(2000);
            System.out.print("P1");
        }
        //rCond.signal();
    }
    catch ( InterruptedException e)
    {
        //System.out.print("Exception ");

        }

    }
    finally
    {
         rl.unlock();
    }
        System.out.print("\n run " + c);
    }

    }

Upvotes: 0

Views: 1919

Answers (1)

Peeyush
Peeyush

Reputation: 432

You are not sharing lock and condition between threads. Each instance of ThreadMy is running with its own lock and condition object.

Upvotes: 1

Related Questions