java - Regarding same Runnable reference on Multiple Treads -
this question has answer here:
when call start()
on thread passing runnable
object argument, can pass same runnable
reference start multiple threads?
public class mymain { public static void main(string[] args) { myrunnableimpl impl = new myrunnableimpl(); new thread(impl).start(); new thread(impl).start(); } }
yes, can when runnable
implemented accordingly.
but have careful runnable
implementation not contain mutable state. can control in own implementations, runnable
contract not specify.
// can used multiple threads class statelessrunnable { public void run() { dosomething(); } } // may go bang on second execution -> use 2 instances class statefulrunnable { volatile boolean canrun = true; public void run() { if(!canrun) throw new illegalstateexception(); canrun = false; } }
in above sample see can use statelessrunnable
many threads like. in fact make singleton. statefulrunnable
in contrast can run only once per instance.
shared state
reading jon's answer realised there may scenarios want share state of 2 runnable
instances. of course stateful runnable
instance not bound fail multiple threads, more trickier right stateless one.
// willingly share state on threads class willinglystatefulrunnable { final blockingqueue<object> sharedobjects = new blockingqueue<object>(); public void run() { sharedobjects.offer(new object()); } }
the above example shows how work on single collection sharedobjects
multiple threads.
literature sidenote:
item 15 in joshau bloch's effective java says minimize mutabilty. chapter - in case have access book - addresses similar points in more general context. shortly summarised states immutable objects make easier reuse instances , reduce potential of illegal states.
Comments
Post a Comment