# _*_ coding:utf-8 _*_
"""
file: 01.py
date: 2018-07-25 1:51 PM
author: westos-dd
desc:
线程是操作系统能够进行运算调度的最小单位(程序执行流的最小单元)
它被包含在进程之中,是进程中的实际运作单位。一个进程中可以并发多个线程
每条线程并行执行不同的任务
(线程是进程中的一个实体,是被系统独立调度和分派的基本单元)
每一个进程启动时都会最先产生一个线程,即主线程
然后主线程会再创建其他的子线程
"""
from time import ctime,sleep
def music(a):
for i in range(2):
print 'I was listening to %s. %s' % (a,ctime())
sleep(1)
def movie(b):
for i in range(2):
print 'I was watching to %s. %s' % (b,ctime())
sleep(5)
music('告白气球')
movie('泰坦尼克号')
print 'all over %s' %ctime()
实验结果
2线程和函数建立关系
# _*_ coding:utf-8 _*_
"""
file:2.py
date:2018-07-25 2:29 PM
author: FATRAT
desc:
"""
from threading import Thread
def Foo(arg):
print arg
print 'before'
# 线程和函数建立关系
t1 = Thread(target=Foo,args=(1,))
t1.start()
print 'after'
3.
# _*_ coding:utf-8 _*_
"""
file: 03.py
date: 2018-07-25 2:24 PM
author: westos-dd
desc:
"""
from threading import Thread
def Foo(arg):
print arg
print 'before'
t1 = Thread(target=Foo,args=(1,))
t1.start()
print t1.getName()
t2 = Thread(target=Foo,args=(2,))
t2.start()
print t2.getName()
print 'after'
实验结果为
/usr/bin/python2.7 /home/kiosk/PycharmProjects/python/day8xia/3.py
before
1Thread-1
2Thread-2
after
Process finished with exit code 0
4.双线程操作
# _*_ coding:utf-8 _*_
"""
file:4.py
date:2018-07-25 2:34 PM
author: FATRAT
desc:
"""
import threading
from time import ctime,sleep
def music(a):
for i in range(2):
print 'I was listening to %s. %s' % (a,ctime())
sleep(1)
def movie(b):
for i in range(2):
print 'I was watching to %s. %s' % (b,ctime())
sleep(5)
#music('告白气球')
#movie('泰坦尼克号')
t1 = threading.Thread(target=music,args=('告白气球',))
t1.start()
t2 = threading.Thread(target=movie,args=('泰坦尼克号',))
t2.start()
print 'all over %s&#