multithreading - Java : One thread needs to wait for other to be done -
i have following use case. can suggest implementation of method t1() assuming run on java 6 ? tried think of accomplishing using wait() , notify() not proper solution. appreciated. (note both of these methods t1() , m1() called in different threads)
class test { static volatile int flag = 0; public static void t1() { //this method called in thread called t2 /*this method must wait flag become 1. becomes 1 must return. should wait maximum n seconds. after if flag 0 must return.*/ } public static void m1() { //this method called in thread called t1 flag = 1; } }
this tried far implementation of t1()
public static void t1() throws interruptedexception { while(flag == 0) { thread.currentthread().sleep(100); } }
above works problem timeout not implemented , while loop not seem good.
use countdownlatch
. initialize before of threads run count one. code this:
class test { static countdownlatch latch = new countdownlatch(1); public static void t1() { //this method called in thread called t2 /*this method must wait flag become 1. becomes 1 must return. should wait maximum n seconds. after if flag 0 must return.*/ latch.await(1l,timeunit.seconds); //your remaining logic } public static void m1() { //your logic latch.countdown(); } }
a countdownlatch
modified, enhanced (e.g. timeout option), , arguably easier-to-understand implementation of semaphore - 1 of basic structures used thread synchronization across number of languages (not java). note following when comparing wikipedia reference java implementation:
p
/wait()
correspondsawait()
, differenceawait()
doesn't changecount
value.v
/signal()
correspondscountdown()
, differencecountdown()
counts down, not (obviously).
Comments
Post a Comment