1Multithreading is a model of program execution
2that allows for multiple threads to be created
3within a process, executing independently but
4concurrently sharing process resources.
5Depending on the hardware, threads can run
6fully parallel if they are distributed to their own CPU core.
1import threading
2
3def func1():
4 # your function
5def func2():
6 # your function
7if __name__ == '__main__':
8 threading.Thread(target=func1).start()
9 threading.Thread(target=func2).start()
1import logging
2import threading
3import time
4
5def thread_function(name):
6 logging.info("Thread %s: starting", name)
7 time.sleep(2)
8 logging.info("Thread %s: finishing", name)
9
10if __name__ == "__main__":
11 format = "%(asctime)s: %(message)s"
12 logging.basicConfig(format=format, level=logging.INFO,
13 datefmt="%H:%M:%S")
14
15 threads = list()
16 for index in range(3):
17 logging.info("Main : create and start thread %d.", index)
18 x = threading.Thread(target=thread_function, args=(index,))
19 threads.append(x)
20 x.start()
21
22 for index, thread in enumerate(threads):
23 logging.info("Main : before joining thread %d.", index)
24 thread.join()
25 logging.info("Main : thread %d done", index)
26
1from multiprocessing.pool import ThreadPool
2
3def stringFunction(value):
4 my_str = 3 + value
5 return my_str
6
7
8def stringFunctio(value):
9 my_str = 33 + value
10 return my_str
11
12pool = ThreadPool(processes=2)
13
14thread1 = pool.apply_async(stringFunction,(8,))
15thread2 = pool.apply_async(stringFunctio,(8,))
16
17return_val = thread1.get()
18return_val1 = thread2.get()
1class RunnableDemo implements Runnable {
2 private Thread t;
3 private String threadName;
4
5 RunnableDemo( String name) {
6 threadName = name;
7 System.out.println("Creating " + threadName );
8 }
9
10 public void run() {
11 System.out.println("Running " + threadName );
12 try {
13 for(int i = 4; i > 0; i--) {
14 System.out.println("Thread: " + threadName + ", " + i);
15 // Let the thread sleep for a while.
16 Thread.sleep(50);
17 }
18 } catch (InterruptedException e) {
19 System.out.println("Thread " + threadName + " interrupted.");
20 }
21 System.out.println("Thread " + threadName + " exiting.");
22 }
23
24 public void start () {
25 System.out.println("Starting " + threadName );
26 if (t == null) {
27 t = new Thread (this, threadName);
28 t.start ();
29 }
30 }
31}
32
33public class TestThread {
34
35 public static void main(String args[]) {
36 RunnableDemo R1 = new RunnableDemo( "Thread-1");
37 R1.start();
38
39 RunnableDemo R2 = new RunnableDemo( "Thread-2");
40 R2.start();
41 }
42}