码迷,mamicode.com
首页 > 编程语言 > 详细

线程与进程

时间:2019-05-24 00:34:58      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:lap   进程   重写   sleep   使用   event   code   方法   display   

一、线程

1、启动方法:

方法一:

步骤1、实例化,t1 = threading.Thread(targe=func, args=())

步骤2、t1.start()

例子:

技术图片
import threading
import time


def run(n):
    print(in the task %s % n)
    print(当前线程是\033[31;1m%s\033[0m % threading.current_thread())
    time.sleep(3)


t1 = threading.Thread(target=run, args=(1,))  # 注意args参数最后要加逗号
t2 = threading.Thread(target=run, args=(2,))
t1.start()
t2.start()
print(当前活跃的线程有\033[31;1m%s\033[0m个 % threading.active_count())
print(当前线程是\033[31;1m%s\033[0m % threading.current_thread())
View Code

方法二:

步骤1、定义一个类,继承threading.Thread,并且重写run

步骤2、使用实例中的start()方法

例子:

技术图片
import threading
import time


class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()
        self.n = n

    def run(self):
        print(现在在线程%s上 % self.n)
        time.sleep(2)


t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
View Code

 

线程与进程

标签:lap   进程   重写   sleep   使用   event   code   方法   display   

原文地址:https://www.cnblogs.com/Treelight/p/10915439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!