1.创建一个子线程

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg):
    while 1:
        print arg,
        time.sleep(1)
        sys.stdout.flush()

t = Thread(target = thread_fun, args = ('*'))
t.start()
while 1:
    print '.',
    time.sleep(1)
    sys.stdout.flush()

运行结果:
Python学习笔记:线程

注:需要kill -9杀死子线程

2.等待子线程结束

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg1,arg2):
    while arg2:
        print arg1,
        time.sleep(1)
        sys.stdout.flush()
	arg2 -= 1

t = Thread(target = thread_fun, args = ('*',20))
t.start()
i = 10
while i:
    print '.',
    time.sleep(1)
    sys.stdout.flush()
    i -= 1
t.join()

运行结果:
Python学习笔记:线程

3.线程模块

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg1,arg2):
    while arg2:
        print arg1,
        time.sleep(1)
        sys.stdout.flush()
	arg2 -= 1
print currentThread()
print '现在的活动线程数是:%d'%activeCount()
t = Thread(target = thread_fun, args = ('*',20))
t.start()
print '新创建的线程名是:',t.getName()
print '现在的活动线程数是:%d'%activeCount()
i = 10
while i:
    print '.',
    time.sleep(1)
    sys.stdout.flush()
    i -= 1
print '现在的活动线程数是:%d'%activeCount()
t.join()
print '现在的活动线程数是:%d'%activeCount()

运行结果:
Python学习笔记:线程

4.线程池的实现

参考文献:https://blog.csdn.net/yongh701/article/details/51313119

#!/user/bin/python
#coding:utf-8
from threading import *
mutex_lock = RLock()
import sys
import time
import random
ticket = 700
class mythread(Thread):
    thread_counter = 0
    def __init__(self,name,index):
        Thread.__init__(self)
        self.name = name
        self.index = index
        mythread.thread_counter += 1
    def run(self):
        global ticket
        global mutex_lock
        tm = random.randint(1,999)/1000.0
        time.sleep(tm)
        mutex_lock.acquire()
        if ticket > 0:
            ticket -= 1
            print self.index,'抢到票了...'
            print '还剩%d张票...'%ticket
        else:
            print self.index,'没有抢到票...'
        mutex_lock.release()
threads = []
for i in range(1,1000):
    t = mythread('thread-'+str(i),i)
    threads.append(t)
for i in threads:
    i.start()
    print '\033[1;32m',i.index,'\033[0m',
    pass
for i in threads:
    i.join()
    print '\033[1;31m',i.index,'\033[0m',
    pass

运行结果:
Python学习笔记:线程

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2021-04-05
  • 2021-05-05
  • 2021-09-26
  • 2021-12-27
猜你喜欢
  • 2021-04-19
  • 2021-05-14
  • 2022-01-06
  • 2021-11-06
  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
相关资源
相似解决方案