Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to use Thread.join

I'm new to threads. How can I get t.join to work, whereby the thread calling it waits until t is done executing?

This code would just freeze the program, because the thread is waiting for itself to die, right?

public static void main(String[] args) throws InterruptedException {
    Thread t0 = new Thready();
    t0.start();

}

@Override
public void run() {
    for (String s : info) {
        try {
            join();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s %s%n", getName(), s);
    }   
}

What would I do if I wanted to have two threads, one of which prints out half the info array, then waits for the other to finish before doing the rest?

like image 336
Nick Heiner Avatar asked Dec 15 '09 16:12

Nick Heiner


People also ask

How do you join a thread in Java?

Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. join() will make sure that t is terminated before the next instruction is executed by the program.

What does the thread join () method do?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

How do I join multiple threads?

You can Join multiple threads by using Thread. join() method. Join is particularly useful to make one thread wait for another, or serializing two functions e.g. first load your cache and then start processing the request.

Can we join two threads?

You can join two threads in Java by using the join() method from java. lang. Thread class.


1 Answers

Use something like this:

public void executeMultiThread(int numThreads)
   throws Exception
{
    List threads = new ArrayList();

    for (int i = 0; i < numThreads; i++)
    {
        Thread t = new Thread(new Runnable()
        {
            public void run()
            {
                // do your work
            }
        });

        // System.out.println("STARTING: " + t);
        t.start();
        threads.add(t);
    }

    for (int i = 0; i < threads.size(); i++)
    {
        // Big number to wait so this can be debugged
        // System.out.println("JOINING: " + threads.get(i));
        ((Thread)threads.get(i)).join(1000000);
    }
like image 98
Francis Upton IV Avatar answered Oct 24 '22 23:10

Francis Upton IV