java – 执行两个线程,在主线程继续时等待另一个线程

如何启动thread1首先执行的两个线程,thread2在thread1结束时启动,而main方法线程可以继续工作而不锁定另外两个?

我已经尝试了join()但是它需要从线程调用,它必须等待另一个,没有办法像thread2.join(thread1)那样做;
如果我在main()中调用连接,那么我有效​​地停止执行主线程,而不仅仅是thread2.

因此,我尝试使用ExecutorService,但同样的问题.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test
{
    public static void main(String args[]) throws InterruptedException
    {
        System.out.println(Thread.currentThread().getName() + " is Started");

        class TestThread extends Thread
        {
            String name;
            public TestThread(String name)
            {
                this.name = name;
            }

            @Override
            public void run()
            {
                try
                {
                    System.out.println(this + " is Started");
                    Thread.sleep(2000);
                    System.out.println(this + " is Completed");
                }
                catch (InterruptedException ex)  {  ex.printStackTrace(); }
            }

            @Override
            public String toString()  { return "Thread " + name; }
        }

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(new TestThread("1"));

        boolean finished = executor.awaitTermination(1, TimeUnit.HOURS);

        if(finished)
        {
           //I should execute thread 2 only after thread 1 has finished
            executor.execute(new TestThread("2"));
        }

        //I should arrive here while process 1 and 2 go on with their execution
        System.out.println("Hello");
    }
}

#EDIT:为什么我需要这个:

我需要这个,因为Thread1将数据库表中的元素复制到另一个数据库中,thread2必须复制一个引用从thread1复制的表的链接表.
因此,thread2只有在thread1完成时才开始填充其链接表,否则数据库会给出完整性错误.
现在想象一下,由于复杂的链接表,我有几个不同优先级的线程,你有一个想法.

最佳答案
第二个Thread可以像这样自定义(作为前一个线程的参数):

public static void main(String[] a) {
    Thread first = new Thread(new Runnable() {
        @Override
        public void run() {

        }
    });

    Thread second = new MyThread(first);
    first.start();
    second.start();

    //continue executing
}

public static class MyThread extends Thread {

    private Thread predecessor;

    public MyThread(Thread predecessor) {
        this.predecessor = predecessor;
    }

    public void run() {
        if (predecessor != null && predecessor.isAlive()) {
            try {
                predecessor.join();
            } catch (InterruptedException e) {}
        }
        //do your stuff
    }
}

转载注明原文:java – 执行两个线程,在主线程继续时等待另一个线程 - 代码日志