当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Thread start()用法及代码示例


Python Thread.start() 方法

Thread.start() 方法是 Python 中线程模块的 Thread 类的内置方法。它用于启动线程的活动。此方法在内部调用 run() 方法,然后执行目标方法。对于一个线程,此方法最多只能调用一次。如果它被多次调用,则会引发 RuntimeError。

模块:

    from threading import Thread

用法:

    start()

参数:

  • None

返回值:

这个方法的返回类型是<class 'NoneType'>,它不返回任何东西。

例:

# Python program to explain the
# use of start() method in Thread class

import time
import threading

def thread_1(i):
    time.sleep(5)
    print('Value by Thread 1:', i)

def thread_2(i):
    print('Value by Thread 2:', i)
    
# Creating two sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))

# Starting two threads
thread1.start()
thread2.start()

输出

Value by Thread 2:2
Value by Thread 1:1

例:

# Python program to explain the
# use of start() method in Thread class

import threading

def thread_1(i):
    print('Value by Thread 1:', i)

def thread_2(i):
    print('Value by Thread 2:', i)

def thread_3(i):
    print('Value by Thread 3:', i)    

    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))
thread3 = threading.Thread(target=thread_3, args=(3,))

# Starting three threads
thread1.start()
thread2.start()
thread3.start()
    
thread1.start()

输出

Value by Thread 1:1
Value by Thread 2:2
Value by Thread 3:3
Traceback (most recent call last):
  File "main.py", line 26, in <module>
    thread1.start()
  File "/usr/lib/python3.8/threading.py", line 848, in start
    raise RuntimeError("threads can only be started once")
RuntimeError:threads can only be started once


相关用法


注:本文由纯净天空筛选整理自 Python Thread Class | start() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。