Creation K Creation K - 7 months ago 15
Java Question

How can I limit the thread behavior to the method that calls them?

Consider this sample class:

public class Multithreading extends Thread {
static int i = 0;

public static void main(String args[]) throws InterruptedException {

call1();
call2();
}

private static void call2() {

Multithreading call2obj1 = new Multithreading() {
public void run() {

}
};
call2obj1.start();

}

private static void call1() {

Multithreading call1obj1 = new Multithreading() {
public void run() {
System.out.println("call1obj1");
sleep(5000);
}
};
Multithreading call1obj2 = new Multithreading() {
public void run() {
System.out.println("call1obj2");
sleep(5000);
}
};
call1obj1.start();
call1obj2.start();

}
}


What I want is for
call2()
to wait until
call1()
is fully complete. i.e.,
call1obj2
need not wait until
call1obj1
is done executing, but
call2obj1
should wait until both
call1obj1
and
call1obj2
are done.

Basically the thread behavior of
call1obj1
and
call1obj2
must be limited to
call1()
;

Is that possible?

Answer

Here is a solution using CountDownLatch:

public class Multithreading extends Thread {
static int i = 0;

private static CountDownLatch LATCH;

public static void main(String args[]) throws InterruptedException {

    // Initialize the latch with the number of threads to finish
    LATCH = new CountDownLatch(2);

    call1();

    // Main thread will wait until all thread finished
    LATCH.await();

    call2();
}

private static void call2() {

    Multithreading call2obj1 = new Multithreading() {
        public void run() {
            System.out.println("call2obj1");
        }
    };
    call2obj1.start();

}

private static void call1() {

    Multithreading call1obj1 = new Multithreading() {
        public void run() {
            System.out.println("call1obj1");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LATCH.countDown();
            }
        }
    };
    Multithreading call1obj2 = new Multithreading() {
        public void run() {
            System.out.println("call1obj2");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LATCH.countDown();
            }
        }
    };
    call1obj1.start();
    call1obj2.start();

}

}