多线程(三)Join

Join

使用join方法可以手工控制,让一个线程等待另一个线程运行完毕再继续。

thread.join();


如果一个线程中包含代码:

t.join();//导致当前线程暂停,等待线程t执行完毕。

很显然,join也会抛interruptedException。


看完以上的内容,我们就可以看一个包含了上述概念的实际的多线程例子:

 http://download.oracle.com/javase/tutorial/essential/concurrency/simple.html

 看上去很长其实很简单,要耐心看~

 public class SimpleThreads {

    //Display a message, preceded by the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    private static class MessageLoop implements Runnable {
        public void run() {
            String importantInfo[] = {
                "Mares eat oats",
                "Does eat oats",
                "Little lambs eat ivy",
                "A kid will eat ivy too"
            };
            try {
                for (int i = 0; i < importantInfo.length; i++) {
                    //Pause for 4 seconds
                    Thread.sleep(4000);
                    //Print a message
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("I wasn't done!");
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {


        //Delay, in milliseconds before we interrupt MessageLoop
        //thread (default one hour).
        long patience = 1000 * 60 * 60;

        //If command line argument present, gives patience in seconds.
        if (args.length > 0) {
            try {
                patience = Long.parseLong(args[0]) * 1000;
            } catch (NumberFormatException e) {
                System.err.println("Argument must be an integer.");
                System.exit(1);
            }

        }

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MessageLoop());//MessageLoop()必须是runnable同时有run方法。
        t.start(); //子线程启动,开始循环打印String数组里的内容。

        threadMessage("Waiting for MessageLoop thread to finish");
        //loop until MessageLoop thread exits
        while (t.isAlive()) {
            threadMessage("Still waiting..."); 
            //在超过时限之前会一直打印这句话
            //Wait maximum of 1 second for MessageLoop thread to
            //finish.
            t.join(1000); //这句的效果和sleep(1000)一样
            if (((System.currentTimeMillis() - startTime) > patience) &&
                    t.isAlive()) {
                threadMessage("Tired of waiting!");
                t.interrupt(); //interrupt方法会中断线程。此时子线程会提示"I wasn't done!",然后被停止。
                //Shouldn't be long now -- wait indefinitely
                t.join(); //join方法的功能是,当前主线程会等待子线程t结束。不过应该很快。
            }

        }
        threadMessage("Finally!"); //最后程序结束。
    }
}

当主线程运行完所有语句,但是有非守护子线程还在运行时,主线程就会一直等待。

(有一点例外。。。如果主线程中最后一句是return。。。那主线程就会立即结束了,从而程序会立即结束)

如果只有守护子线程运行,守护子线程就会结束,之后主线程就运行完毕了。

运行结果:

传入参数为2时

main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
main: Still waiting...
main: Still waiting...
main: Tired of waiting!
Thread-0: I wasn't done!
main: Finally!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值