Multithreading

Mode 1

import threading  # import
import time


def fun1(a):
    for i in range(10):
        print(threading.current_thread().getName(), i)
        # time.sleep(a)


def fun2(a):
    for i in range(65, 76):
        print(threading.current_thread().getName(), chr(i))
        # time.sleep(a)


thread1 = threading.Thread(target=fun1, args=(1,),
                           name="threading 1")  # Only the function name is passed, not the parameter
thread2 = threading.Thread(target=fun2, args=(1,), name="threading 2")

thread1.start()
thread2.start()

Mode 2

import threading  # import
import time


def fun1(a):
    for i in range(10):
        print(threading.current_thread().getName(), i)
        # time.sleep(a)


def fun2(a):
    for i in range(65, 76):
        print(threading.current_thread().getName(), chr(i))
        # time.sleep(a)


class MyThread1(threading.Thread):
    def __init__(self, a, name):
        super().__init__(name=name)
        self.a = a

    def run(self):
        fun1(self.a)


class MyThread2(threading.Thread):
    def __init__(self, a, name):
        super().__init__(name=name)
        self.a = a

    def run(self):
        fun2(self.a)


thread1 = MyThread1(0.1, "threading 1")
thread1.start()

thread2 = MyThread2(0.1, "threading 2")
thread2.start()    

Jion

import threading


def fun1():
    for i in range(10):
        print(threading.current_thread().getName(), i)
        if i == 5:
            thread2 = threading.Thread(target=fun2, name="threading 2")
            thread2.start()
            thread2.join()


def fun2():
    for i in range(65, 76):
        print(threading.current_thread().getName(), chr(i))


thread1 = threading.Thread(target=fun1, name="threading 1")
thread1.start()
threading 1 0
threading 1 1
threading 1 2
threading 1 3
threading 1 4
threading 1 5
threading 2 A
threading 2 B
threading 2 C
threading 2 D
threading 2 E
threading 2 F
threading 2 G
threading 2 H
threading 2 I
threading 2 J
threading 2 K
threading 1 6
threading 1 7
threading 1 8
threading 1 9
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值