Reputation: 3731
I need help with my Uni assignment that involves threads. In the assignment, I have to implement a program that contains 4 threads, and one of those threads contains another thread. I've made a diagram below to help explain it better:
What would be the best/efficient way to do this? My prof gave a very limited explanation on threads, and from what I've gathered so far on the web, I would have to implement the Runnable interface, and create 4 classes from within the main program's run() method, which will probably end up in a mess because I still do not fully grasp the concept of threads in Java. If anyone can suggest a resource where I would be able to learn more, please post it here.
Here's an example of my understanding so far:
public class MainThread implements Runnable
{
/**
* The run method from the Runnable interface that
* executes the entire program.
*/
public void run()
{
class Controller implements Runnable
{
public void run()
{
class MiniWalker implements Runnable
{
public void run ()
{
}
}
}
}
class ObjectWalker implements Runnable
{
public void run ()
{
}
}
class GroupWalker implements Runnable
{
public void run ()
{
}
}
class YearWalker implements Runnable
{
public void run ()
{
}
}
}
/**
* The heart and core of this assignment.
*/
public static void main(String[] args)
{
(new Thread(new MainThread ())).start();
}
}
Upvotes: 2
Views: 1437
Reputation: 4443
Concurrent Programming by Doug Lee is another good resource (and virtually all of it is free on google books). It is also worth looking at an ExecutorService or a ForkJoinPool. Also, read through the javadocs they are pretty decent.
It might be worth trying to break up your application into what would essentially be tasks and just throw them into a thread pool.
Upvotes: 0
Reputation: 15046
The good place to start is http://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html . It will give you basic understanding of concurrency in java. Without describing what this thread do (why do you need to create them) it is hard to write which choice would be optimal.
It is worth mentioning that you can spawn threads without explicilty coding new class.
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
}
Upvotes: 0
Reputation: 53694
Threads don't contain other threads. Threads can control other threads, but that's entirely different. Your control diagram does not have to relate directly to your class hierarchy.
Upvotes: 3
Reputation: 308743
I'd recommend that you read Brian Goetz' "Java Concurrency In Practice" and dig into the concurrency classes under java.util (e.g. Executor). They'll make your life better than raw threads.
Upvotes: 1