當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。