Thread.join()

即使子线程休眠了,也不去抢cpu资源,等子线程做完了主线程再做,t.start()是关键代码,要先开启

public class Test5
{
    public static void main(String[] args)
    {
        MyRunnable2 r = new MyRunnable2();
        Thread t = new Thread(r, "子线程");
        t.start();
        try
        {   //合并线程
            t.join(4000);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        r.run();
    }
}
class MyRunnable2 implements Runnable
{
    @Override
    public void run()
    {
        for (int i = 0; i < 30; i++)
        {
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
    
}
posted @ 2019-12-29 14:07  奇异宝  阅读(148)  评论(0编辑  收藏  举报