写一个python多线程demo

坚果1年前 ⋅ 1168 阅读
```python
# import threading module
import threading

# class with a thread
class ThreadedFunction(threading.Thread):

    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    # run the thread
    def run(self):
        print("Starting " + self.name)
        for x in range(self.counter):
            # Do something
            print("Doing something in thread: " + self.name)

# Create new threads
thread1 = ThreadedFunction(1, "Thread 1", 3)
thread2 = ThreadedFunction(2, "Thread 2", 3)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads = []
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
    t.join()

print("Exiting Main Thread")

```

全部评论: 0

    相关推荐