Thread.join

 

JAVA代码实例:

import java.util.concurrent.TimeUnit;

public class JoinDemo2 {

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

        Thread thread2 = new Thread(() -> {
            try {
                System.out.println("执行线程2");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread1 = new Thread(() -> {
            try {
                thread2.join();
                System.out.println("执行线程1");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        System.out.println("执行后续结果");
    }
}

PYTHON代码实例

import threading
import time

exitFlag = 0


class MyThread(threading.Thread):
    def __init__(self, thread_id, name, counter, pre_thread=None):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name
        self.counter = counter
        self.pre_thread = pre_thread

    def run(self):
        if self.pre_thread is not None:
            self.pre_thread.join()
        print("开始线程:\t" + self.name)
        print_time(self.name, 1, self.counter)
        print("退出线程:\t" + self.name)


def print_time(thread_name, delay, counter):
    while counter:
        if exitFlag:
            thread_name.exit()
        time.sleep(delay)
        print("%s: %s" % (thread_name, time.ctime(time.time())))
        counter -= 1


thread2 = MyThread(2, "线程2", 10)
thread1 = MyThread(1, "线程1", 10, thread2)
thread2.start()
thread1.start()

thread1.join()
thread2.join()
print("退出")

 

执行结果:

JAVA执行结果

PYTHON执行结果

执行流程图:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值