Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

concurrency - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...