0
package Pack3;

public class Test4 {

    public static void main(String[] args) {

        final Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                    System.out.println("Main Thread Started !!");

                try {
                    synchronized (this) {
                        System.out.println("Waiting Mode ");
                        this.wait();
                        System.out.println("Main thread exited");
                    }
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }

            }
        });

        t.start();

        Thread[] t1 = new Thread[10];
        for (int i = 0; i < 10; i++) {
            t1[i] = new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "Executed");
                }
            });

            if (i == 9) {

                synchronized (t1[i]) {
                    t1[i].notifyAll();
                    t1[i].start();
                }

            } else {
                t1[i].start();
            }
        }
    }

}

Output is :

Main Thread Started !!
Waiting Mode 
Thread-1Executed
Thread-2Executed
Thread-4Executed
Thread-3Executed
Thread-6Executed
Thread-7Executed
Thread-5Executed
Thread-8Executed
Thread-9Executed
Thread-10Executed

But t(Main Thread) is not exited ? Why?

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
Keval Pithva
  • 600
  • 2
  • 5
  • 21
  • What is the question exactly? – TheLostMind Jan 12 '16 at 05:28
  • If you now the number of threads, you could use a `CountDownLatch`, if not you could use a `ExecutorService` of some kind – MadProgrammer Jan 12 '16 at 05:29
  • *"But t(Main Thread) is not exited ? Why?"* - Because `this.wait()` is never been notified – MadProgrammer Jan 12 '16 at 05:30
  • I want to wake my main thread(t) again How can I wake up it? – Keval Pithva Jan 12 '16 at 05:39
  • Something like this might help: http://stackoverflow.com/questions/34456633/wait-main-thread-until-one-of-out-many-threads-signals-in-java/34456666#34456666 – markspace Jan 12 '16 at 05:43
  • You can set all those threads as non-daemon thread then your program will only exit when all the threads have ended their execution, but this is risky as you might end up in never ending loop if something goes wrong (i.e. in your code if you have bug, not sure from the OS side). You might want to take measures on how to prevent a thread from being existing continuously – Bilbo Baggins Jan 12 '16 at 05:49
  • Can you please provide code ? – Keval Pithva Jan 12 '16 at 06:27
  • Programme definition is "Hold the main thread execution until another threads are being executed" – Keval Pithva Jan 12 '16 at 06:28

0 Answers0