Threads within threads in Java?

末鹿安然 提交于 2019-11-26 21:19:44

问题


I am currently thinking about how to design a multithreading system in Java that needs to do some heavy network processing and database storage. The program will launch three basic threads at first. Along these basic threads, I would like to launch other threads not from the main program but from two of the threads. Is it possible for a thread to launch another thread leading to some sort of a hierarchy like:

> Parent ->t0 thread1 -> t1 tread1.1  
>        ->t0 thread2
>        ->t0 thread3 -> t2 thread3.1

t0= inital time
t1,t2 = time at a point in the running thread
t1 != t2 

If not could somebody provide a theoretical solution with references?


回答1:


Yes, you can launch as many threads as you want, but that's probably not the best way to go. It's much better to use the non-blocking API's so that you can start execution of some external call and the calling thread can immediately start doing something else without waiting on the socket/database call to come back. Then, when the socket/database call comes back, a callback is triggered to finish that processing.

Non-blocking I/O can provide far superior CPU utilization since you're just triggering calls and registering callbacks and not having to try to balance the "right" number of concurrent threads which are mostly just sleeping anyways.

http://www.owlmountain.com/tutorials/NonBlockingIo.htm

http://www.tensegrity.hellblazer.com/2008/03/non-blocking-jdbc-non-blocking-servlet-apis-and-other-high-mysteries.html




回答2:


To answer the question, yes threads can launch other threads.

Is the hierarchy important?

You're probably better off using an ExecutorService with a cached thread pool. That way you can pool threads instead of creating lots (which is expensive). ExecutorServices also provide other cool things, and using Callables / Runnables with them is probably much easier to test than mucking about with threads on your own.




回答3:


Yes a thread can launch another thread, and that thread can launch thread(s) and on and on...

In the run() method of a thread - you can create and start other threads.




回答4:


It's possible for exemple you can creat thread and put id in array like this

UnThread[] tab=   new  UnThread[10] ;

for ( int i=0;i<20;i++)

tab[i] = new UnThread();

After you can give to the subMainThread the array tab

exemple

  while( tab[1].isAlive() ) {
  //do somthing..
  System.out.println("Ligne affichée par le main");
  try {
    // et faire une pause
    tab[1].sleep(800);
  }
  catch (InterruptedException ex) {}
 }

here a simple use of thread : http://kamel.berrayah.com/wordpress/2013/07/java-threads/



来源:https://stackoverflow.com/questions/7224670/threads-within-threads-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!