python基础-线程创建方式

python中提供了两种创建线程的方式

1.采用thread.start_new_thread(funciton,args..)

2.集成Thread类

第一种方式

import thread as t
import time

#Define a function for the thread
def print_time(threadName,delay):
    count=0;
    while count<5:
        time.sleep(delay)
        count+=1
        print "%s(%s): %s " %(threadName,count,time.ctime(time.time()))

#Create two threads as follows
try:
    t.start_new_thread(print_time,("thread-1",2))
    t.start_new_thread(print_time,("thread-2",3))
except:
    print "Error:unable to start thread"

while 1:
    pass

2.继承Thread

实现步骤如下

  1. 申明一个Thread类的子类
  2. 覆盖_init_(slef,agrs)方法来增加额外的参数
  3. 实现线程逻辑

但是有一个奇怪的问题是,run和start方式有很大的差别

import threading
import time

exitFlag=0

class myThread(threading.Thread):
    #implement thead
    def __init__(self,threadID,name,delay):
        threading.Thread.__init__(self)
        self.threadID=threadID
        self.name=name
        self.delay=delay

    def run(self):
        print "Starting "+ self.name
        print_time(self.name,self.delay,5)
        print "Exiting "+ self.name

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

#Create new threads
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",3)

#start
thread1.start()
thread2.start()#run和start不同,why?

while thread2.isAlive():
    if not thread1.isAlive():
        exitFlag = 1
        print "thread1 is over"
    pass
print "Exiting Main Thread"

线程同步

时间: 2024-08-10 19:05:37

python基础-线程创建方式的相关文章

Python菜鸟之路:Python基础-线程、进程、协程

上节内容,简单的介绍了线程和进程,并且介绍了Python中的GIL机制.本节详细介绍线程.进程以及协程的概念及实现. 线程 基本使用 方法1: 创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入 import threading import time def worker(): time.sleep(2) print("test") for i in range(5): t = threading.Thread(target=

MFC 线程创建方式

MFC 分UI线程和工作线程,一般现在的应用程序都是一个主UI线程和N个工作线程来完成工作.主UI线程获取到工作线程发送的信息来刷新界面. 不过因为工作需要,MFC有要维护的项目,因此就学习一下MFC创建UI线程,使用工作线程的方式. 1.UI线程,继承CWinThread类  1 class CAddDeviceApp : public CWinThread 2 { 3     DECLARE_DYNCREATE(CAddDeviceApp) 4 protected: 5     CAddDe

java多线程(一)-五种线程创建方式

简单使用示例 Java 提供了三种创建线程的方法: 通过实现 Runnable 接口: 通过继承 Thread 类本身: 通过 Callable 和 Future 创建线程. 还有 定时器 线程池 下面第一个类给出了四种创建方式,第二个类是定时器示例. ① public class ThreadStartTest { public static void main(String[] args) throws ExecutionException, InterruptedException { S

Python基础—线程、进程和协程

今天已是学习Python的第十一天,来干一碗鸡汤继续今天的内容,今天的鸡汤是:超越别人对你的期望.本篇博客主要介绍以下几点内容: 线程的基本使用: 线程的锁机制: 生产者消费之模型(队列): 如何自定义线程池: 进程的基本使用: 进程的锁机制: 进程之间如何实现数据共享: 进程池: 协程的基本使用. 一.线程 1.创建线程 上篇博客已经介绍过如何创建多线程的程序,在这里在复习一下如何创建线程过程以及线程的一些方法: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1

Python菜鸟之路:Python基础-线程池注释

import sys import threading import Queue import traceback # 定义一些Exception,用于自定义异常处理 class NoResultsPending(Exception): """All works requests have been processed""" pass class NoWorkersAvailable(Exception): """N

Java 线程创建方式

Java创建线程有两种方式 1.通过Runnable接口实现(推荐的方式) (1)新建一个类实现Runnable接口,需要重写run方法 1 class MyRunnable implements Runnable{ 2 3 @Override 4 public void run() { 5 6 } 7 8 } (2)新建一个线程对象,在构造器中传入实现了Runnable接口的类 Thread thread = new Thread(new MyRunnable); (3)调用Thread的st

Java并发编程(01):线程的创建方式,状态周期管理

本文源码:GitHub·点这里 || GitEE·点这里 一.并发编程简介 1.基础概念 程序 与计算机系统操作有关的计算机程序.规程.规则,以及可能有的文件.文档及数据. 进程 进程是计算机中的程序,关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机结构中,进程是程序的基本执行实体:在面向线程设计的计算机结构中,进程是线程的容器.程序是指令.数据及其组织形式的描述,进程是程序的实体. 线程 线程是操作系统能够进行运算调度的最小单

java_10:线程创建的方式二

除了继承Thread类和实现Runnable接口两种创建线程的方式,JDK5.0还新增类两种线程创建方式: 新增方式一:实现Callable接口 好处:(1)与使用Runnable相比,Callable功能更强大些(2)相比run()方法,可以有返回值(3)方法可以抛出异常(4)支持泛型的返回值(5)需要借助FutureTask类,比如获取返回结果Future接口:1)可以对具体的Runnable\Callable任务的执行结果进行取消.查询是否完成.获取结果等2)FutureTask是Futu

【Python与线程】 -- 2019-08-16 21:12:56

原文: http://blog.gqylpy.com/gqy/232 " ? 目录 一.全局解释器锁GIL 二.Python线程模块的选择 三.线程的创建 三.锁机制 四.信号量 五.事件 六.条件 七.定时器 八.线程队列 九.线程池 补充:线程安全 import threading obj = threading.local() # local():可实现,多线程操作某一数据,不会出现数据混乱的情况 # 原理:空间换时间 def add(i): obj.n = i print(i, obj.