Python Multithreading (practice)

Source: Internet
Author: User

Objective:

The above is a single thread, now will be a multi-threaded, directly on the code:

1. Create a threading. A subclass of thread to wrap a thread object

#encoding: UTF8

Import threading

Import time

Class Timer (threading. Thread):

def __init__ (Self,num,interval):

Threading. Thread.__init__ (self)

#设置产生线程的个数

Self.thread_num = num

#产生线程的相隔时间

Self.interval = Interval

Self.thread_stop = False

def run (self):

While not self.thread_stop:

print ' Thread Object (%d), time:%s\n '% (Self.thread_num,time.ctime ())

Time.sleep (Self.interval)

def stop (self):

Self.thread_stop = True

def test ():

Thread1 = timer (up to)

Thread2 = Timer (2,2)

Thread1.start ()

Thread2.start ()

Time.sleep (10)

Thread1.stop ()

Thread2.stop ()

Return

if __name__ = = ' __main__ ':

Test ()

Operation Result:

Threading. Use of the thread class:

1). Call threading in the __init__ of your own thread class. Thread.__init__ (self, name = ThreadName)

ThreadName is the name of the thread

2). Run (), which usually requires rewriting and writing code to implement the required functionality.

3). GetName (), get the Thread object name

4). SetName (), set thread object name

5). Start (), starting thread

6). Jion ([timeout]), wait for another thread to finish before running.

7). Setdaemon (bool), set whether the child thread ends with the main thread and must be called before start (). The default is False.

8). Isdaemon () to determine if the thread has ended with the main threads.

9). IsAlive () to check if the thread is running.

In addition, the threading module itself provides a number of methods and other classes that can help us better use and manage threads

I'll talk to you tomorrow.

Simple synchronization

Python Multithreading (practice)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.