I am trying to run 4 threads in sequence like 4 -> 3 -> 2 -> 1. And I am using int threadId and AtomicInteger to validate if the current thread is eligible to run or not. But the 4th thread starts and the execution gets stuck, I am not getting why the thread 3, 2 and 1 are not getting a chance to run.
Here is what I did:
public class SequenceDemo implements Runnable{
int threadId;
static AtomicInteger currentThread = new AtomicInteger(4);
ReentrantLock lock;
Condition condition;
public SequenceDemo( ReentrantLock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}
@Override
public void run() {
try {
lock.lock();
threadId = Integer.parseInt(Thread.currentThread().getName());
while(currentThread.get()!=threadId) {
condition.await();
}
System.out.println("Thread "+Thread.currentThread().getName()+" started executing");
Thread.sleep(1000);
System.out.println("Thread "+Thread.currentThread().getName()+" finished executing");
currentThread.decrementAndGet();
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
SequenceDemo demo1 = new SequenceDemo(lock, condition);
Thread t1 = new Thread(demo1, "1");
Thread t2 = new Thread(demo1, "2");
Thread t3 = new Thread(demo1, "3");
Thread t4 = new Thread(demo1, "4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
output: Execution gets stuck after execution of thread 4:
Thread 4 started executing
Thread 4 finished executing
Your code is fine, you should just pass a new SequenceDemo instance to each thread, otherwise they share the threadId and it's just stuck on the value 4 for all threads. (Took me a few minutes to see haha)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With