android - Java Class Cast Exception thrown even though the cast-from parent class is actually an instance of the cast-to subclass -
i'm trying cast returned thread object java's threadfactory.newthread(runnable r) specific subclass of thread android application uses, follows:
private threadfactory mvthreadsource = executors.defaultthreadfactory(); ... //invokes thread factory's newthread(runnable r) method //mvthreadsvector arraylist<backgroundthread> //class backgroundthread extends thread , implements interface public void spawnbgthreads(int numthreads){ (int i=0;i<numthreads;i++){ mvthreadsvector.add((backgroundthread) mvthreadsource.newthread(new backgroundthread())); } }
this throws class cast exception, i'm not sure why; know i'm seemingly attempting downcast can't done, thread returned mvthreadsource.newthread(new backgroundthread()) should instance of backgroundthread. understanding should create legal 'downcast' effort above (because shouldn't downcasting), android runtime (targeting sdk revision 17) disagrees. illegal above cast? alternative approach should utilize (hopefully short of creating own backgroundthreadfactory class extends threadfactory)?
but thread returned mvthreadsource.newthread(new backgroundthread()) should instance of backgroundthread
what makes think that?
what makes think it's thought pass in instance of thread
threadfactory.newthread
in first place? in cases, creating thread
instances without starting them can lead memory leaks, believe. (quite perchance not on android, mind you.)
there's reason why parameter threadfactory.newthread
of type runnable
instead of thread
- it's meant "the action should run" rather thread. it's threadfactory
's job create thread run action - that's why it's called threadfactory
:)
you could create own threadfactory
created backgroundthread
instances, it's not clear why want in first place. what's actual requirement here? perhaps should not building list<backgroundthread>
instead list<backgroundrunnable>
backgroundrunnable
interface extends runnable
, has whatever methods want on it...
java android classcastexception
No comments:
Post a Comment