Threading Examples In Python3

1.How To Create A Thread By Using _thread in Python3.

import _thread
import time

def printing(tName, delay, counter):
    while counter:
         time.sleep(delay)
         print ("%s: %s" % (tName, time.ctime(time.time())))
         counter -= 1
try:
    _thread.start_new_thread(printing("One",1,3))
    _thread.start_new_thread(printing("Two",1,3))
except Exception:
    print(Exception)

2.How To Create A Thread By Using threading in Python3.

import threading
import time
class First(threading.Thread):
        def run(self):
            for i in range(10):
                print("i=",i,"time",time.ctime())
                time.sleep(1)

class Second(threading.Thread):
    def run(self):
        for j in range(10):
            print("j=", j, "time", time.ctime())
            print(threading.current_thread())
            time.sleep(1)
f = First()
f.start()
#f.run()
f.setName("First")
print(f.getName())

s=Second()
#s.run()
s.start()
s.setName("Second")
print(s.getName())

print("Count=",threading.active_count())
print("enumerate",threading.enumerate())


#if(f.isAlive):
 #   f.join()
#print(f.isAlive)
#f.run()


#if(s.isAlive):
 #   s.join()
#print(s.isAlive)
#s.run()

3.How To Create A Thread By Using threading Another Example in Python3.

 import threading
import time

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

   def run(self):
      threadLock.acquire()
      printing(self.name, self.counter, 3)

      threadLock.release()

def printing(tName, delay, counter):
   while counter:
      time.sleep(delay)
      print ("%s: %s" % (tName, time.ctime(time.time())))
      counter -= 1



threadLock = threading.Lock()

threads = []

thread1 = myThread(1, "First", 1)
thread2 = myThread(2, "Second", 2)

thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)

for t in threads:
   t.join()