Walmart Labs Interview Question
Applications DevelopersCountry: India
Interview Type: In-Person
There is one more solution with CountDownLatch.
public class ThreadJoinTest {
@Test
public void testThreadJoin() {
ThreadJoin t = new ThreadJoin(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(3);
} catch(InterruptedException e) {
System.err.println(e.getMessage());
}
System.out.println("Task has been finished");
}
});
t.start();
t.threadJoin();
assertThat(t.getState(), is(equalTo(Thread.State.TERMINATED)));
}
}
public class ThreadJoin extends Thread {
private CountDownLatch latch = new CountDownLatch(1);
public ThreadJoin(Runnable runnable) {
super(runnable);
}
@Override
public void run() {
super.run();
latch.countDown();
}
public void threadJoin() {
try {
latch.await();
} catch (InterruptedException e) {
System.err.println("Exception occured while joining");
e.printStackTrace();
}
}
}
You will have write the code by yourself using wait() and Notify() to implement the functionality same as join. yes we can do it.
- Soumitrav December 04, 2014