Search code examples
javamultithreadingjava-threads

Multi-threading: Program create 10 threads and calls method print thread make sure the output of this method do not interrupt each other


Above prog is working by calling both wait() and join(). Can you tell me which method I should use. Or is there a better way to write this program .Thanks in advance :) For thread.wait() I create a syncronized block before calling t.start().

public class DisplayThread {

    public synchronized void printThread(int threadNumber){
        System.out.println("I am thread number: " + threadNumber);

    }
}


public class Thread1 extends Thread {

    DisplayThread d;
    int num;

    Thread1(DisplayThread d, int num) {
        this.d = d;
        this.num = num;
    }

    public void run() {
        d.printThread(num);
    }

    public static void main(String[] args) {

        DisplayThread d = new DisplayThread();
        Thread[] t = new Thread[10];

        for (int i = 0; i < 10; i++) {
            t[i] = new Thread1(d, i);
            t[i].start();
            try {
                t[i].join();  **//t[i].wait(1000) also works fine**
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}

Solution

  • If your goal is to have the 10 Threads execute concurrently, you'll need to move the Thread#join call outside of the initial loop.

    for (int i = 0; i < 10; i++) {
        t[i] = new Thread1(d, i);
        t[i].start();
    }
    
    for (int i = 0; i < 10; i++) {
        try {
            t[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    Other than that, everything looks fine to me!