multithreading - A Thread as an object Java -
i want collection of objects inherit thread
; each object running in it's own thread.
i tried extends thread
, called super()
thinking that'd ensure new thread created; no... main
running thread :(
everyone tells me, "implement runnable
put code want in run()
, put in thread-object". can't because of 2-reasons:
my collection-elements aren't of-type
thread
, if polymorph i'll have change it's dependencies.run()
can't contain entire class... right?
so want know firstly, if want possible , secondly, if so, how it?
super()
calls parent constructor (in case default thread
constructor). method start new thread start()
. others have said, it's poor design extend thread
.
yes, can create class implements runnable
class myspecialthread implements runnable { public void run() { // } }
and can start in new thread this:
thread t = new thread(new myspecialthread()); // add collection, track etc. t.start(); // starts new thread
1- can use collections of runnables
or collections of thread
s using example below.
myspecialthread m = new myspecialthread(); list<runnable> runnables = new arraylist<runnable>(); runnables.add(m); list<thread> threads = new arraylist<thread>(); threads.add(new thread(m));
2- method can't contain class, above example myspecialthread
class behaves other class. can write constructor, add methods , fields, etc.
Comments
Post a Comment