• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

threading issue

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
consider there is a program in which several threads are running.i want to modify the program in such a manner that when the main thread terminates all other threads have been terminated and i don't want to scan the file.Only i want to add some lines of code at the closing brace of main(like calling join on each of the live thread.)
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy,

Pralad:


when the main thread terminates all other threads have been terminated


I don't understand your question.
Do you want that all threads will be stopped when the main thread terminates,


or

Do you want that the main thread terminates only if all other threads are already terminated.



?


Bu.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


when the main thread terminates all other threads have been terminated


I didn't quite get what you meant about not wanting to scan. But if you call setDeamon(true) on the threads, they will not keep running when main thread stops since it's the thread that spawned them if that makes any sense. Not sure if that's the answer you were looking for. You should probably clarify your question as both the last poster and I weren't quite able to understand what you meant. If you have the main thread call join on the threads just after their respective start() are called, the main will in essence wait for them to end to 'connect' itself to the end of their execution. Is that what you're looking for?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please do not post the same question to more than one forum.
 
Prahlad Joshi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i want to ensure that whenever the main thread terminates all the child threads are already dead and i have tried the following (is it correct?).
or if there is any other method please tell me.

package newpackage;
public class Exp extends Thread{
public static void main(String args[])
{

Thread t=new Exp();
t.setName("one");
Thread t1=new Exp();
t1.setName("two");
Thread t2=new Exp();
t2.setName("three");
Thread t3=new Exp();
t3.setName("Four");
t.start();
t1.start();
t2.start();
t3.start();




Thread [] activeThreads=newThread[Thread.currentThread().activeCount()];
Thread.currentThread().getThreadGroup().enumerate(activeThreads);
for(Thread th:activeThreads)

{try
{if(th.getName().equals("main"))
continue;
th.join();
}catch(InterruptedException i)
{

}
}
System.out.println("main thread terminate");

}

public void run()
{
try
{
Thread.sleep(10000);
}catch(InterruptedException ie)
{

}
System.out.println("in thread "+Thread.currentThread().getName());
}
}
P.S. Sorry for the inconvenience i will try to be more clear in my next posts and wouldn't post the same topic in more than one forum.
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Prahlad,

Your approach is basically sound. Aside from perhaps doing some minor code cleanup here and there (e.g. using Thread.activeCount() instead of Thread.currentThread().activeCount()), the only problem I see is that you're not properly handling the InterruptedException that join() might throw. If you get interrupted, the thread you were trying to join may not yet have terminated, so you need to re-invoke join() on the same thread to be safe.

Here's one way of addressing this problem (extracted from code I posted in another thread):
 
Prahlad Joshi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Kelvin it was really helpful.I think that the main problem with my approach is that i am considering only the immediate child threads of main.
If the main's child thread also have children and so on(creating a tree kind of structure) this approach fails(or have to write a recursive routine using the original approach).
e.g.
package newpackage;
public class Exp extends Thread{
public static void main(String args[])
{

Thread t=new Exp();
t.setName("one");
Thread t1=new Exp();
t1.setName("two");
Thread t2=new Exp();
t2.setName("three");
Thread t3=new Exp();
t3.setName("Four");
t.start();
t1.start();
t2.start();
t3.start();




Thread [] activeThreads=new Thread[Thread.activeCount()];
Thread.currentThread().getThreadGroup().enumerate(activeThreads);
for(Thread th:activeThreads)
{
if(th.getName().equals("main"))
continue;
else
{boolean joined=false;
do
{try

{

th.join();
joined=true;

}catch(InterruptedException i){}



}while(!joined);


}

}
System.out.println("main thread terminates");
}

public void run()
{
try
{
Thread.sleep(10000);
}catch(InterruptedException ie)
{

}
System.out.println("in thread "+Thread.currentThread().getName());
Thread t1=new Thread(new subt());
t1.start();


}
}
class subt implements Runnable
{
public void run()
{
try
{
Thread.sleep(10000);
}catch(InterruptedException ie)
{

}
System.out.println("in thread "+Thread.currentThread().getName());
}
}

OUTPUT:
in thread one
in thread two
in thread three
in thread Four
main thread terminate
in thread Thread-4
in thread Thread-5
in thread Thread-6
in thread Thread-7

but if somehow we can get hold of no. of active user threads(let's assume there is a function getTotalActiveThreads()) then we can write just above closing brace of main
while(1)
{
if(getTotalActiveThreads()>1)
{
Thread.sleep(1000);
continue;
}
else
break;
}
System.out.println("main thread terminates");
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem isn't so much the fact that the threads are "hierarchical", but rather it's that additional threads may be started after you populate your activeThreads array. Here's one possible way to work around the problem:

Incidentally, you should also note that there are at least two problems with all of the approaches discussed so far:
  • They only work if all the threads belong to the same thread group as the main thread
  • There is a race condition in this sequence of statements: "Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads);".

  • [ December 06, 2007: Message edited by: Kelvin Lim ]
     
    Prahlad Joshi
    Ranch Hand
    Posts: 44
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    package newpackage;
    public class Exp2 extends Thread{
    public static void main(String args[])
    {

    Thread t=new Exp2();
    t.setName("one");
    Thread t1=new Exp2();
    t1.setName("two");
    Thread t2=new Exp2();
    t2.setName("three");
    Thread t3=new Exp2();
    t3.setName("Four");
    t.start();
    t1.start();
    t2.start();
    t3.start();
    while (Thread.activeCount() > 1) {
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);

    Thread th = null;
    for (int i = 0; i < threads.length; i++) {
    if (threads[0] != Thread.currentThread()) {
    th = threads[0];
    break;
    }
    }

    if (th != null) {
    boolean joined=false;
    do {
    try {
    th.join();
    joined = true;
    } catch(InterruptedException i) {}
    } while(!joined);
    }
    }
    System.out.println("main thread terminates"+Thread.currentThread().toString());
    }

    public void run()
    {
    try
    {
    Thread.sleep(10000);
    }catch(InterruptedException ie)
    {

    }
    System.out.println("in thread "+Thread.currentThread().toString());
    ThreadGroup tg1=new ThreadGroup("tg1");

    Thread t1=new Thread(tg1,new subt());

    t1.start();




    }
    }
    class subt implements Runnable
    {
    public void run()
    {
    try
    {
    Thread.sleep(10000);
    }catch(InterruptedException ie)
    {

    }
    System.out.println("in thread "+Thread.currentThread().toString());
    }
    }

    produces the desired output:
    in thread Thread[one,5,main]
    in thread Thread[two,5,main]
    in thread Thread[three,5,main]
    in thread Thread[Four,5,main]
    in thread Thread[Thread-4,5,tg1]
    in thread Thread[Thread-5,5,tg1]
    in thread Thread[Thread-6,5,tg1]
    in thread Thread[Thread-7,5,tg1]
    main thread terminatesThread[main,5,main]

    and i think we can replace
    while (Thread.activeCount() > 1) {
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);

    Thread th = null;
    for (int i = 0; i < threads.length; i++) {
    if (threads[0] != Thread.currentThread()) {
    th = threads[0];
    break;
    }
    }

    if (th != null) {
    boolean joined=false;
    do {
    try {
    th.join();
    joined = true;
    } catch(InterruptedException i) {}
    } while(!joined);
    }
    }

    by while (Thread.activeCount() > 1);
     
    Kelvin Chenhao Lim
    Ranch Hand
    Posts: 513
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Prahlad Joshi:
    and i think we can replace
    while (Thread.activeCount() > 1) {
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);

    Thread th = null;
    for (int i = 0; i < threads.length; i++) {
    if (threads[0] != Thread.currentThread()) {
    th = threads[0];
    break;
    }
    }

    if (th != null) {
    boolean joined=false;
    do {
    try {
    th.join();
    joined = true;
    } catch(InterruptedException i) {}
    } while(!joined);
    }
    }

    by while (Thread.activeCount() > 1);



    No, you should not do that. The "while (Thread.activeCount() > 1);" statement is a spin-wait loop, which means this thread will remain runnable and will thus consume CPU cycles needlessly while looping. If you call th.join(), this thread will be put into the non-runnable state and the scheduler will not run it until it gets interrupted or the thread th dies.
     
    Prahlad Joshi
    Ranch Hand
    Posts: 44
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    thanks kelvin i never thought about that
     
    Ranch Hand
    Posts: 621
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hi thr


    I have a doubt regarding the above thread program
    here the main issue is to terminate all the threads
    before main thread complete
    i am confused with this part of code
    as below


    please explain where i am actualy going wrong?


    thanks in advance.
     
    Prahlad Joshi
    Ranch Hand
    Posts: 44
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    main thread is spawning child threads and the array is containing reference to these child threads to ensure that main terminate last we are calling join on each of the child thread one by one form the main thread.
    e.g.
    main thread has 3 child threads thread1,thread2,thread3
    then we are calling join on thread1,thread2,thread3 one by one(e.g. thread1.join ,thread2.join,thread3.join (not necessarily in this sequence) ) and the thread which is doing this is the main thread and when all the join call returns it means they have finished and then the main thread terminates.
     
    dhwani mathur
    Ranch Hand
    Posts: 621
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks prahlad joshi
    for your explanation.
    i am now clear with my
    doubts.


    Dhwani->Its always too soon to quit.
     
    Everybody's invited. Except this tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic