Presentation is loading. Please wait.

Presentation is loading. Please wait.

Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.

Similar presentations


Presentation on theme: "Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously."— Presentation transcript:

1 Threading in Java – a Tutorial QMUL IEEE SB

2 Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously Process vs Thread (OS concept)

3 Lifecycle of a Thread Ref: http://www.tutorialspoint.com/java/java_multithreading.htm http://www.tutorialspoint.com/java/java_multithreading.htm

4 Creating a Thread Two ways: – Implement Runnable interface – Extend Thread class Creating Thread using Runnable interface, – method: public void run() – All the code for the thread goes here – We can call other methods, make objects of other classes etc within run() – the class that implements Runnable creates an instance of Thread class Thread(Runnable threadOb, String threadName);

5 Example - Creating Thread by Implementing Runnable Ref: http://www.tutorialspoint.com/java/java_multithreading.htm http://www.tutorialspoint.com/java/java_multithreading.htm

6

7

8 Output - Creating Thread by Implementing Runnable

9 Create thread by Extending Thread Create a class that extends Thread override the run( ) method call start( ) to begin execution of the new thread

10 Example - Create thread by Extending Thread Ref: http://www.tutorialspoint.com/java/java_multithreading.htm http://www.tutorialspoint.com/java/java_multithreading.htm

11 Output - Create thread by Extending Thread

12 Creating multiple Threads

13 Output - Creating multiple Threads

14 Thread Synchronization Ensuring only one of two or more competing threads get access to the resource Synchronized statement in java synchronized(object) { // statements to be synchronized }

15 Example Code - Synch.java

16 Output - Thread Synchronization

17 Output - Same Example with Unsynchronized Threads

18 Example Code - UnSynch.java

19 References Java – Multithreading, http://www.tutorialspoint.com/java/java_mul tithreading.htm http://www.tutorialspoint.com/java/java_mul tithreading.htm Java - Thread Synchronization, http://www.tutorialspoint.com/java/java_thre ad_synchronization.htm http://www.tutorialspoint.com/java/java_thre ad_synchronization.htm Multithreading, http://www.ccs.neu.edu/course/com3118/Mu ltithreading.html http://www.ccs.neu.edu/course/com3118/Mu ltithreading.html


Download ppt "Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously."

Similar presentations


Ads by Google