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.
1class Count implements Runnable
2{
3 Thread mythread ;
4 Count()
5 {
6 mythread = new Thread(this, "my runnable thread");
7 System.out.println("my thread created" + mythread);
8 mythread.start();
9 }
10 public void run()
11 {
12 try
13 {
14 for (int i=0 ;i<10;i++)
15 {
16 System.out.println("Printing the count " + i);
17 Thread.sleep(1000);
18 }
19 }
20 catch(InterruptedException e)
21 {
22 System.out.println("my thread interrupted");
23 }
24 System.out.println("mythread run is over" );
25 }
26}
27class RunnableExample
28{
29 public static void main(String args[])
30 {
31 Count cnt = new Count();
32 try
33 {
34 while(cnt.mythread.isAlive())
35 {
36 System.out.println("Main thread will be alive till the child thread is live");
37 Thread.sleep(1500);
38 }
39 }
40 catch(InterruptedException e)
41 {
42 System.out.println("Main thread interrupted");
43 }
44 System.out.println("Main thread run is over" );
45 }
46}
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
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()
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()