Java & J2EE More About Multithreading in Java |
Before we begin, it’s worth noting that this article is a sequel, so it presumes sound knowledge of the things we learned in the prior part. That part of the series was also published here, so should you have any doubts, please refer back to it. There are three kinds of variable types to which threads have access. The first type is local variables, but these are private, meaning that the threads cannot access each other’s variables; plus, if more threads are running the same snippet, then each thread has its own copies of the local variables. Then we have object attributes and static attributes. The latter are reachable by all threads. Object attributes can be shared (explicitly), if necessary. Since we can work with multiple threads, it makes sense that Java allows more than one thread to be grouped. When we are working with a huge number of threads, this actually simplifies our job, since we can manage threads by their group. Say we’re juggling five threads, and they’re all part of a ThreadGroup. It’s so much easier to stop them by calling the method via the group, rather than doing so independently. Moreover, we can hierarchically add groups of threads into one thread group. This is how the entire concept turns into a tree-like hierarchy. It should be noted that threads can only access information from their own ThreadGroup, but not their parent’s or other’s. We can work with Threads just like we would with arrays or sets. Let’s see the following example:
class MyThread extends Thread{ public MyThread (String name){ super(name); }
public void run(){ try{ for(int i = 0; i < 10; ++i) sleep(1000); } catch(InterruptedException e){} } }
class MyThreadGroup{ public static void main (String args[]){ MyThread t[] = new MyThread[10]; for (int i = 0; i < 10; ++i) t[i] = new MyThread("Thread no: " + i); for (int i = 0; i < 10; i+=2) t[i].start(); ThreadGroup grp = Thread.currentThread().getThreadGroup(); int instanceCount = grp.activeCount(); Thread th[] = new Thread[instanceCount]; int activeCount = grp.enumerate(th); System.out.println("Thread Group Name: " + grp.getName()); System.out.println("Count of Threads: " + instanceCount); System.out.println("Count of Active Threads: " + activeCount); System.out.println("List of Active Threads: "); for (int i = 0; i < activeCount; ++i) System.out.println(th[i].getName()); grp.interrupt(); } }
And guess what, the above code snippet has the following output:
Thread Group name: main Count of Threads: 6 Count of Active Threads: 6 List of Active Threads: main Thread no: 0 Thread no: 2 Thread no: 4 Thread no: 6 Thread no: 8 Now it’s time for us to continue with some advanced ideas.
blog comments powered by Disqus |
|
|
|
|
|
|
|