Java并发编程实例--6.线程的join方法

有时我们需要等到某个线程执行完毕。例如,我可能有一个线程来初始化资源完毕然后其他线程才能开始执行。
谓词,我们可以使用Thread类的join()方法。

本例中,我们将学习使用这个方法。


DataSourcesLoader.java

package com.dylan.thread.ch1.c06;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xusucheng
 * @create 2018-04-25
 **/
public class DataSourcesLoader implements Runnable{
    @Override
    public void run() {
        System.out.printf("Beginning data sources loading: %s\n",new
                Date());
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Data sources loading has finished: %s\n",new Date());
    }
}


NetworkConnectionsLoader.java

package com.dylan.thread.ch1.c06;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xusucheng
 * @create 2018-04-25
 **/
public class NetworkConnectionsLoader implements Runnable {
    @Override
    public void run() {
        // Writes a message
        System.out.printf("Begining network connections loading: %s\n",new Date());
        // Sleep six seconds
        try {
            TimeUnit.SECONDS.sleep(6);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Writes a message
        System.out.printf("Network connections loading has finished: %s\n",new Date());
    }
}

Main.java

package com.dylan.thread.ch1.c06;

import java.util.Date;

/**
 * @author xusucheng
 * @create 2018-04-25
 **/
public class Main {
    public static void main(String[] args) {
        DataSourcesLoader dsLoader = new DataSourcesLoader();
        Thread thread1 = new Thread(dsLoader,"DataSourceThread");
        NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
        Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Main: Configuration has been loaded: %s\n",new Date());
    }
}


输出:

Beginning data sources loading: Wed Apr 25 23:11:50 CST 2018
Begining network connections loading: Wed Apr 25 23:11:50 CST 2018
Data sources loading has finished: Wed Apr 25 23:11:54 CST 2018
Network connections loading has finished: Wed Apr 25 23:11:56 CST 2018
Main: Configuration has been loaded: Wed Apr 25 23:11:56 CST 2018






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值