python多线程有几种实现方法

python多线程有几种实现方法,都是什么?

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。2.7版本之前python对线程的支持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading  模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。

一般来说,使用线程有两种模式:

A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;

B 继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。

第一种 创建函数并且传入Thread 对象中

    import threading,time
    from time import sleep, ctime
    def now() :
        return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

    def test(nloop, nsec):
        print 'start loop', nloop, 'at:', now()
        sleep(nsec)
        print 'loop', nloop, 'done at:', now()

    def main():
        print 'starting at:',now()
        threadpool=[]

        for i in xrange(10):
            th = threading.Thread(target= test,args= (i,2))
            threadpool.append(th)

        for th in threadpool:
            th.start()

        for th in threadpool :
            threading.Thread.join( th )

        print 'all Done at:', now()

    if __name__ == '__main__':
            main()

第二种是创建一个新的class,将要执行的代码 写到run函数里面。

    import threading ,time
    from time import sleep, ctime
    def now() :
        return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

    class myThread (threading.Thread) :
          """docstring for myThread"""
          def __init__(self, nloop, nsec) :
              super(myThread, self).__init__()
              self.nloop = nloop
              self.nsec = nsec

          def run(self):
              print 'start loop', self.nloop, 'at:', ctime()
              sleep(self.nsec)
              print 'loop', self.nloop, 'done at:', ctime()
    def main():
         thpool=[]
         print 'starting at:',now()

         for i in xrange(10):
             thpool.append(myThread(i,2))

         for th in thpool:
             th.start()

         for th in thpool:
             th.join()

         print 'all Done at:', now()

    if __name__ == '__main__':
            main()
时间: 2024-08-03 10:43:53

python多线程有几种实现方法的相关文章

多线程有几种实现方法?同步有几种实现方法?(被问到)

多线程有两种实现方法,分别是继承Thread类与实现Runnable接口 同步的实现方面有两种,分别是synchronized,wait与notify wait():使一个线程处于等待状态,并且释放所持有的对象的lock. sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用此方法要捕捉InterruptedException异常. notify():唤醒一个处于等待状态的线程,注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且

java多线程有几种实现方法,都是什么?

转自:http://www.cnblogs.com/liujichang/p/3150387.html 多线程有两种实现方法,分别是继承Thread类与实现Runnable接口 同步的实现方法有两种,分别是synchronized,wait与notify 先看一下java线程运行时各个阶段的运行状态 java实现多线程有两种方法 1.继承Thread类 2.实现Runnable接口 这两种方法的共同点: 不论用哪种方法,都必须用Thread(如果是Thead子类就用它本身)产生线程,然后再调用s

多线程有几种实现方法?同步有几种实现方法?

多线程有两种实现方法,分别是继承Thread类与实现Runnable接口 同步的实现方面有两种,分别是synchronized,wait与notify wait():使一个线程处于等待状态,并且释放所持有的对象的lock. sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用此方法要捕捉InterruptedException异常. notify():唤醒一个处于等待状态的线程,注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且

java中实现多线程的两种基本方法

java中实现多线程有两种基本方法,一种是继承Thread, 另一种是实现Runnable接口. 但是因为java中子类只能继承一个父类,如果采用继承Thread类,就不能继承其他类,很受限制. 以下是采用继承Thread类的例子: public class MyThreadTest{ public static void main(String[] args){ MyThread amythread1=new MyThread("my thread 1"); MyThread amy

python多线程编程之Queue---put/get 方法的阻塞

python 中,队列是线程间最常用的交换数据的形式.Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外. 1. 阻塞模式导致数据污染 import Queue       q = Queue.Queue(10)       for i in range(10):               myData = 'A'               q.put(myData)               myData = 'B' 这是一段极其简单的代码,但我总是不能

python多线程的几种方法

python多线程编程 Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间 2.isAlive()方法:查看线程是否还在运行 3.getName()方法:获得线程名 4.setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon() Pytho

java多线程有几种实现方法?线程之间如何同步

java中多线程的实现方法有两种:1.直接继承thread类:2.实现runnable接口: 同步的实现方法有五种:1.同步方法:2.同步代码块:3.使用特殊域变量(volatile)实现线程同步:4.使用重入锁实现线程同步:5.使用局部变量实现线程同步 .其中多线程实现过程中需注意重写或者覆盖run()方法,而对于同步的实现方法中使用较常使用的是利用synchronized编写同步方法和代码块.

Python单例模式的4种实现方法

#-*- encoding=utf-8 -*- print '----------------------方法1--------------------------' #方法1,实现__new__方法 #并在将一个类的实例绑定到类变量_instance上, #如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回 #如果cls._instance不为None,直接返回cls._instance class Singleton(object): def __new__(

多线程有几种同步有几种实现方法,都是什么?

多线程有几种实现方法,都是什么?同步有几种实现方法,都是什么? 多线程有两种实现方法,分别是继承Thread类与实现Runnable接口同步的实现方面有两种,分别是synchronized,wait与notify 关于Cookie的路径及Cookie的获取问题? Cookie c1=new Cookie"cname","c1"); c1.setPath"/MyApp"); c1.setMaxAgeInteger.MAX_VALUE); respo