now going thread process,i have 1 thread , i'll run thread several time increasing count. if stop thread using thread instincts stop processing thread.
here had tried:
if (null != image && server.threadcount <=10) { startthread = new thread(mthread); startthread.start(); } else { server.threadcount--; } } public static class runnablethread implements runnable { public void run() { server.threadcount++; /* if (server.threadcount <=10) { log.v("count",string.valueof(server.threadcount)); server.threadcount++; } */ } } }
if use startthread.interrupt(); stop hole thread or current.
i need stop particular thread , if need stop whole thread.
this alternate solution provide here. first of must warn using count threads error prone , dangerous. may miss decrement or incrementing variable due concurrency issue. provide here solution above problem , alternate solution problem.
solution question :
first thing is, in above example have reference 1 thread when call startthread.interrupt(), result stop 1 thread have referenced @ time.
second suggest add reference list, specially concurrent collection or synchronized collection. can iterate thread references list , call interrupt() when wanted flag interruption.
ex :
list<thread> threadlist = collections.synchronizedlist(new arraylist<thread>()); ...... startthread = new thread(mthread); startthread.start(); threadlist.add(startthread); ...... @override public void ondestroy() { super.ondestroy(); synchronized(threadlist) { iterator<string> iterator = threadlist.iterator(); while (iterator.hasnext()) thread startthread = iterator.next(); startthread.interrupt(); }}
- stop thread according interrupted flag.
alternate , preferred solution :
create threadpool number of threads wanted use. can call shutdown() or shutdownnow()method achieve above.this call interrupts threads processing tasks. ex:
executorservice executer = executors.newfixedthreadpool(10); executor.execute(yourrunnablehere); /*if have 10 can use loop execute runnables. */ ....... @override public void ondestroy() { super.ondestroy(); executor.shutdownnow(); }
in above example create threadpool.
- a threadpool pool of threads. submitted or executed tasks on executors processed threads threadpool. above create threadpool of 10 threads. 10 tasks can executed in parallel executor.
- the executors used manage execution of tasks. used interrupt thread. short intro above example.
you can learn more executors , threadpool online or reading book "java concurrency in practice" , android "efficient android threading". hope helped. thank you.
short tutorial on executor :
you can use below link learn executors or other concurrency utilities quickly. gives knowledge 1 concurrency utilities. note: check side navigation bar other utilities.
Comments
Post a Comment