0

I need to write a java program that creates a thread to print integers 1 - 3 inclusive. When 2 is printed, the thread waits until a second thread has finished before printing 3. The second thread prints the letter z three times.

possible outputs include: 1z2zz3 z1z2z3 12zzz3

How can I wait for a thread to finish?

user253751
  • 57,427
  • 7
  • 48
  • 90
Ruth l
  • 13
  • 1

6 Answers6

1

Here is a solution for your task. With synchronized and wait you can solve this.

        public static void main(String[] args) {
               new PrintingTheads().doJob();
         }

      }



    class PrintingTheads{
        private    Object objsynch= new Object();
        private  int numberofZ = 0;

        public void doJob(){
            new Thread(){
                public void run(){

                    while(true){
                      System.out.print(1); Thread.yield(); // thread yeald is here for better "mixing the number 1,2 and Z letters"
                       System.out.print(2);Thread.yield();
                       synchronized (objsynch) {
                            while(numberofZ!=3) try{objsynch.wait(10);} catch(InterruptedException e){}

                        }

                       System.out.println(3);
                       try{Thread.sleep(1000);} catch(InterruptedException e){}  // * this part is only for easy to see what happened and can be deleted
                       synchronized (objsynch) {
                          numberofZ = 0;
                          objsynch.notifyAll();
                        }
                    }

                    }

             }.start();


             new Thread(){
                 public void run(){

                     while(true){
                        synchronized (objsynch) {
                            while(numberofZ!=0) try{objsynch.wait(10);} catch(InterruptedException e){}
                        }
                        for(int i= 0;i<3;i++) {System.out.print('z');Thread.yield();}

                        synchronized (objsynch) {
                          numberofZ=3;
                          objsynch.notifyAll();
                        }
                     }
                 }

             }.start();
        }
    }
0

You can call the join method on a Thread object to wait for it to finish. Example:

public class JoinTest implements Runnable {
    public static void main(String[] args) throws Exception {
         System.out.println("in main");
         Thread secondThread = new Thread(new JoinTest());
         secondThread.start();
         secondThread.join();
         System.out.println("join returned");
    }

    @Override
    public void run() {
        System.out.println("second thread started");
        // wait a few seconds for demonstration purposes
        try {
            Thread.sleep(3000);
        } catch(InterruptedException e) {}
        System.out.println("second thread exiting");
    }
}

Note: it doesn't matter whether you choose to extend Thread or implement Runnable for this - any Thread object can be joined.

The output should be:

in main
second thread started

and then 3 seconds later:

second thread exiting
join returned
user253751
  • 57,427
  • 7
  • 48
  • 90
  • Hi, thanks for your answer, but could you also tell me how this ties in with the number printing itself? I don't quite get how the thread will stop printing at two and wait for the second thread to finish, how is that going to be implemented? Thanks again! – Ruth l Mar 06 '15 at 05:38
  • @RuthI After printing 2, and before printing 3, it will call `join` on the "z" thread... – user253751 Mar 06 '15 at 05:39
0

You need some kind of synchronisation mechanism. Commonly a semaphore or mutex.

Eg.

Semaphore mutex = new java.util.concurrent.Semaphore(1); // 1 - means single resource

In counting thread

{
    for (int i = 1; i < 3; i++) {
        System.print("i");
        if (i == 2) {
            // wait for other thread to finish
            mutex.acquire();
        }
    }
    System.println();  // Output newline at end.    
}

in 'zzz' thread

{
    // This should be done before the other thread starts
    // and will make it wait when it wants to acquire the mutex.
    mutex.acquire();
    for (int i = 1; i < 3; i++) {
        System.print("z");
    }
    // Allow the other thread to acquire the mutex.
    mutex.release();
}

Please excuse if my syntax is not 100% java, and no exception handling.

Richard
  • 52
  • 3
0

check this

public class Test {
    private static int number=1;
    private static int z=1;
    private static Thread t2;


    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {

            public void run() {
                for (int i = 0; i <= 20; i++) {
                    if (number == 3){
                        while (z<4);

                    }
                    System.out.print(number++);
                    if (number == 4){
                        number = 1;
                        z=1;
                    }
                }
                t2.stop();
            }
        });
        t2 = new Thread(new Runnable() {

            public void run() {
                while(true){
                   while(z<=3){
                    System.out.print("z");
                    z++;
                  }
                   System.out.print("");
                }
            }
        });
        t.start();
        t2.start();
    }
}
Nooh
  • 1,548
  • 13
  • 21
0

You can use CountDownLatch for that purposes, as example:

import java.util.concurrent.CountDownLatch;

public class Test {

    public static void main(String... s){

        final CountDownLatch cdl = new CountDownLatch(1);

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(1);
                System.out.println(2);
                try {
                    cdl.await();//wait another thread finish
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(3);
            }
        });


        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i=0;i<3;i++)
                    System.out.println("z");
                cdl.countDown();//notify all waiting threads
            }
        });

        t2.start();
        t1.start();
    }

}

outputs: 1zzz23 , z12zz3 ...

alex2410
  • 10,904
  • 3
  • 25
  • 41
-1

I think You want to wait a thread.So you can Put this line inside your run() method.

Thread.sleep(1000);

So every thread will held for 1 sec while completing execution.Hope this will work.Try it and let me know.