Access multiple shared resource with multiple threads in java -
i trying insert values in 3 shared arrays through 2 thread. conditions if array accessed 1 thread thread can use array. example c1, c2, c3 3 arrays , t1 , t2 2 thread if t1 using c1 t2 can not use c1 can use c2 or c3. same condition applied t2. please if knew how code scenario.
as has been commented can use synchronized blocks or alternatively use lock:
lock locka, lockb, lockc; ... if (locka.trylock()) { try { // write c1 } catch (interruptedexception e) { // todo } { locka.unlock(); } } else if (lockb.trylock()) { try { // write c2 } catch (interruptedexception e) { // todo } { lockb.unlock(); } } else if (lockc.trylock()) { try { // write c3 } catch (interruptedexception e) { // todo } { lockc.unlock(); } } else { // cant 3 locked!!! } ...
the trylock()
method returns true if lock available , gives lock thread calling method otherwise returns false.
once thread has lock can perform operation needs on array , no other thread can array during time.
the unlock()
method in finally
block executed once operation has completed frees lock , allows other threads perform operation.
Comments
Post a Comment