Ibtehaz Ibtehaz - 7 months ago 28
Java Question

Wait for one thread to finish in java

I am relatively new Threading in java and I was trying to do the following work. Two Threads will run. Thread1 will print from 1-10 and then wait while Thread2 will finish printing 11-20 and then finishes its task and notify thread1 to print 21-30 and then thread1 will terminate as well.
This is the code I have used:

private Thread thread = null;
private String name = null;
private static Object obj = new Object();
private static int index = 1;

public childThread(Thread t, String name)
{
this.name = name;
this.thread = t;
}
public void run()
{
try
{
while (true) {
Thread.sleep(500);
if (index % 10 == 0 && index == 10) {
System.out.println("Waiting for Thread2");
synchronized (obj) {
obj.notify();
obj.wait();
}
}
else if (index % 10 == 0 && index == 20) {
System.out.println("Waiting for Thread1");
synchronized (obj) {
obj.notify();
obj.wait();
}
}
else if(index == 30)
{
obj.wait();
}


synchronized (obj) {
System.out.println(name + " ><>< " + index);
index++;
}
}
}
catch(Exception e)
{
}


And I am getting the following output:

Thread2 ><>< 1
Thread1 ><>< 2
Thread2 ><>< 3
Thread1 ><>< 4
Thread2 ><>< 5
Thread1 ><>< 6
Thread1 ><>< 7
Thread2 ><>< 8
Thread2 ><>< 9
Thread1 ><>< 10
Thread2 ><>< 11
Thread1 ><>< 12
Thread2 ><>< 13
Thread1 ><>< 14
Thread2 ><>< 15
Thread1 ><>< 16
Thread2 ><>< 17
Thread1 ><>< 18
Thread2 ><>< 19
Waiting for Thread1
Waiting for Thread1
Thread1 ><>< 20
Thread1 ><>< 21
Thread1 ><>< 22
Thread1 ><>< 23
Thread1 ><>< 24
Thread1 ><>< 25
Thread1 ><>< 26
Thread1 ><>< 27
Thread1 ><>< 28
Thread1 ><>< 29


Based on my current understanding in Java threading.

if(index %10 == 0 && index == 10) block will notify the other thread to run and wait while the other completed and same goes for the second one. Now it does not work first time. But when index == 20, thread2 stops working and thread1 continue to print30.

Thanks for your help. :)

Answer

This is a working code, hope this helps

public static void main(String[] args) {
    final Object lock = new Object();
    final Thread t2 = new Thread() {
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            for(int i = 11; i < 21; i++) System.out.println(i);
        }
    };
    Thread t1 = new Thread() {
        public void run() {
            for(int i = 1; i < 11; i++) System.out.println(i);
            synchronized (lock) {
                lock.notifyAll();
            }
            try {
                t2.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for(int i = 21; i < 31; i++) System.out.println(i);
        }
    };
    t1.start();
    t2.start();
}
Comments