www.SunilOS.com 1
www.sunilos.com
www.raystec.com
Concurrency/Threads
Mother’s morning
www.SunilOS.com 2
Concurrency & Threads
1:
2:
3:
4:
6:
single threading
multi threading
1
Threading
www.SunilOS.com 3
Single Threading Multithreading
Thread
Thread
Thread
Thread
Thread
OS
OS
www.SunilOS.com 4
OS
CPU Cycle
Thread
Thread
Thread
Thread
Thread
Thread
Thread
HelloNoThread
1. public class HelloNoThread {
2. String name = null;
3. public HelloNoThread(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 5
TestHelloNoThread
1. public class TestHelloNoThread {
2. public static void main(String[] args) {
3. HelloNoThread t1 = new HelloNoThread("Ram");
4. HelloNoThread t2 = new HelloNoThread("Shyam");
5. t1.run();
6. t2.run();
7. }
8. }
 0 Ram
 1 Ram
 2 Ram
 …..
 48 Ram
 49 Ram
 0 Shyam
 1 Shyam
 2 Shyam
 ……..
 48 Shyam
 49 Shyam
www.SunilOS.com 6
t1.run() t2.run()
Create Thread
www.SunilOS.com 7
Thread
+run()
+start()
+sleep()
MyThread HelloThread Other
+run() +run() +run()
extends
HelloThread
1. public class HelloThread extends Thread{
2. String name = null;
3. public HelloThread(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 8
TestHelloThread
1. public class TestHelloThread{
2. public static void main(String[] args) {
3. HelloThread t1 = new HelloThread("Ram");
4. HelloThread t2 = new HelloThread("Shyam");
5. t1.start();
6. t2.start();
7. for (int i = 0; i < 50; i++) {
8. System.out.println(“main");
9. }
10. }
11.}
 0 Ram
 1 Ram
 2 Ram
 0 Shyam
 1 Shyam
 1 main
 2 main
 3 main
 3 Ram
 4 Ram
 2 Shyam
 3 Shyam
 4 main
 ……..
 48 Ram
 49 Ram
 48 Shyam
www.SunilOS.com 9
CPU Scheduling
CPU
Main
Ram
Shyam
T1 T2 T3
Pani puri –Thread scheduling
www.SunilOS.com 11
OS
CPU Cycle
Ready Thread Queue
Thread
Thread Thread Thread
Thread
Thread Priority
www.SunilOS.com 12
Priority range from 1-10
www.SunilOS.com 13
CPU Cycle
Priority
www.SunilOS.com 14
Set and get priority
 Thread t = new Thread(“Ram”);
o t.setPriority(9);
o int i = t.getPriority();
 Default priority is 5
 Priority constants are defined in Thread class:
o Thread.MIN_PRIORITY=1
o Thread.MAX_PRIORITY=10
o Thread.NORM_PRIORITY=5
Runnable interface
www.SunilOS.com 15
Runnable
+run()
Implements
ParentClass
extends
ChildClass
+run()
Runnable interface
1. public class HelloRunnable implements Runnable {
2. String name = null;
3. public HelloRunnable(String n) {
4. name = n;
5. }
6. public void run() {
7. for (int i = 0; i < 50; i++) {
8. System.out.println(i + name);
9. }
10. }
11.}
www.SunilOS.com 16
Test Runnable
 public class TestHelloRunnable {
 public static void main(String[] args) {
 Thread t1 = new Thread(new HelloRunnable("Ram"));
 Thread t2 = new Thread(new HelloRunnable("Shyam"));
 t1.start();
 t2.start();
 for (int i = 0; i < 500; i++) {
 System.out.println("Main");
 }
 }
 } www.SunilOS.com 17
www.SunilOS.com 18
Threads and Processes
Thread creation
A java program executed as thread inside JVM
A thread can create another thread.
Threads work concurrently.
If one thread dies, other will remain active in
memory
www.SunilOS.com 19
www.SunilOS.com 20
Thread Lifecycle - States
2: start()
finish run()
1: new
Born Blocked
Runnable
Dead
1. I/O available
2. notify()
3. wake up()
1. block on I/O
2. wait()
3. sleep()
www.SunilOS.com 21
Thread Methods
 start()
o Starts the thread and put into runnable queue
 run()
o Performs operation
 Thread.sleep(int m)/sleep(int m,int n)
o Sleeps the thread for given time in milliseconds and nanoseconds
 Thread.yield()
o Pauses currently executing thread and put at last in the runnable queue
www.SunilOS.com 22
Daemon Threads
 Daemon threads are supporting and background threads
 It provides services to normal threads
 Garbage Collector is a Daemon thread.
 t.setDaemon(true)
Daemon
Thread
Normal
Thread
Usage | multi user system
www.SunilOS.com 23
Web Application
Database
Race condition
www.SunilOS.com 24
Thread 1
Thread 2
Object
www.SunilOS.com 25
Race Condition
 Threads of a process can share common memory area
 When two threads simultaneously try to access and modify an
object, it is called race-condition
 The result of a program is affected by the order in which threads
are allocated CPU time and executed
www.SunilOS.com 26
Deposit in the Account
Account
Balance = 1000
Balance = 2000
getBalance():1000
setBalance(2000)
setBalance(2000)
getBalance():1000
getBalance()
CPU
getBalance()
setBalance()
setBalance()
User1 User 2
Deposit
Deposit
www.SunilOS.com 27
Synchronized access
Account
Balance = 1000
Balance = 3000
getBalance():1000
setBalance(2000)
setBalance(3000)
getBalance():2000
User1 User 2
Deposit Deposit
getBalance()
CPU
locked
setBalance()
setBalance()
getBalance()
www.SunilOS.com 28
Account
1. public class Account {
2. private int balance = 0;
3. public int getBalance() {
4. try {
5. Thread.sleep(200);
6. } catch (InterruptedException e) {}
7. return balance;
8. }
9. public void setBalance(int balance) {
10. try {
11. Thread.sleep(200);
12. } catch (InterruptedException e) {}
13. this.balance = balance;
14. }
15.
www.SunilOS.com 29
Account
1. public synchronized void deposit(String msg, int amt) {
2. int bal = getBalance();
3. bal = bal + amt;
4. setBalance(bal);
5. System.out.println(msg + " new balance " + bal);
6. }
7. }
www.SunilOS.com 30
RacingCondThread
public class RacingCondThread extends Thread {
public static Account data = new Account();
String name = null;
public RacingCondThread(String name) {
this.name = name;
}
public void run() {
for(int i=0;i<5;i++){
data.deposit(name, 1000);
}
}
www.SunilOS.com 31
TestRacingCondThread
public static void main(String[] args) {
RacingCondThread t1 = new RacingCondThread(“Ram");
RacingCondThread t2 = new RacingCondThread(“Shyam");
t1.start();
t2.start();
}
Output
 void deposit(..)
o Ram balance 1000
o Shyam balance 1000
o Ram balance 2000
o Shyam balance 2000
o Shyam balance 3000
o Ram balance 3000
o Shyam balance 4000
o Ram balance 4000
o Shyam balance 5000
o Ram balance 5000
 synchronized void deposit(..)
o Ram balance 1000
o Ram balance 2000
o Ram balance 3000
o Ram balance 4000
o Ram balance 5000
o Shyam balance 6000
o Shyam balance 7000
o Shyam balance 8000
o Shyam balance 9000
o Shyam balance 10000
www.SunilOS.com 32
www.SunilOS.com 33
Synchronization types
Method
public synchronized void deposit(String message, int amount)
{….}
Block
public void deposit(String message, int amount) {
synchronized (this){
int bal = getBalance() + amount;
setBalance(bal);
}
System.out.println(message + " Now Bal is " + bal);
}
www.SunilOS.com 34
Monitors / Locks
 It is a lock or token of an object
 The thread has lock, can access object
 Other threads will be in waiting queue
 One object has two monitors or tokens
o One for instance methods, called Object Monitor
o Second for static methods, called Class Monitor
www.SunilOS.com 35
Monitor Keys
Static Sync Methods
x
z
y
Instance Sync Methods
a
c
b
Thread1
Thread2
x() Class
Monitor
y()
a() Object
Monitor
b()
CLASS
Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 36
Thank You!
www.SunilOS.com 37
www.SunilOS.com

Threads V4

  • 1.
  • 2.
    Mother’s morning www.SunilOS.com 2 Concurrency& Threads 1: 2: 3: 4: 6: single threading multi threading 1
  • 3.
    Threading www.SunilOS.com 3 Single ThreadingMultithreading Thread Thread Thread Thread Thread OS OS
  • 4.
  • 5.
    HelloNoThread 1. public classHelloNoThread { 2. String name = null; 3. public HelloNoThread(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 5
  • 6.
    TestHelloNoThread 1. public classTestHelloNoThread { 2. public static void main(String[] args) { 3. HelloNoThread t1 = new HelloNoThread("Ram"); 4. HelloNoThread t2 = new HelloNoThread("Shyam"); 5. t1.run(); 6. t2.run(); 7. } 8. }  0 Ram  1 Ram  2 Ram  …..  48 Ram  49 Ram  0 Shyam  1 Shyam  2 Shyam  ……..  48 Shyam  49 Shyam www.SunilOS.com 6 t1.run() t2.run()
  • 7.
  • 8.
    HelloThread 1. public classHelloThread extends Thread{ 2. String name = null; 3. public HelloThread(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 8
  • 9.
    TestHelloThread 1. public classTestHelloThread{ 2. public static void main(String[] args) { 3. HelloThread t1 = new HelloThread("Ram"); 4. HelloThread t2 = new HelloThread("Shyam"); 5. t1.start(); 6. t2.start(); 7. for (int i = 0; i < 50; i++) { 8. System.out.println(“main"); 9. } 10. } 11.}  0 Ram  1 Ram  2 Ram  0 Shyam  1 Shyam  1 main  2 main  3 main  3 Ram  4 Ram  2 Shyam  3 Shyam  4 main  ……..  48 Ram  49 Ram  48 Shyam www.SunilOS.com 9
  • 10.
  • 11.
    Pani puri –Threadscheduling www.SunilOS.com 11 OS CPU Cycle Ready Thread Queue Thread Thread Thread Thread Thread
  • 12.
  • 13.
    Priority range from1-10 www.SunilOS.com 13 CPU Cycle Priority
  • 14.
    www.SunilOS.com 14 Set andget priority  Thread t = new Thread(“Ram”); o t.setPriority(9); o int i = t.getPriority();  Default priority is 5  Priority constants are defined in Thread class: o Thread.MIN_PRIORITY=1 o Thread.MAX_PRIORITY=10 o Thread.NORM_PRIORITY=5
  • 15.
  • 16.
    Runnable interface 1. publicclass HelloRunnable implements Runnable { 2. String name = null; 3. public HelloRunnable(String n) { 4. name = n; 5. } 6. public void run() { 7. for (int i = 0; i < 50; i++) { 8. System.out.println(i + name); 9. } 10. } 11.} www.SunilOS.com 16
  • 17.
    Test Runnable  publicclass TestHelloRunnable {  public static void main(String[] args) {  Thread t1 = new Thread(new HelloRunnable("Ram"));  Thread t2 = new Thread(new HelloRunnable("Shyam"));  t1.start();  t2.start();  for (int i = 0; i < 500; i++) {  System.out.println("Main");  }  }  } www.SunilOS.com 17
  • 18.
  • 19.
    Thread creation A javaprogram executed as thread inside JVM A thread can create another thread. Threads work concurrently. If one thread dies, other will remain active in memory www.SunilOS.com 19
  • 20.
    www.SunilOS.com 20 Thread Lifecycle- States 2: start() finish run() 1: new Born Blocked Runnable Dead 1. I/O available 2. notify() 3. wake up() 1. block on I/O 2. wait() 3. sleep()
  • 21.
    www.SunilOS.com 21 Thread Methods start() o Starts the thread and put into runnable queue  run() o Performs operation  Thread.sleep(int m)/sleep(int m,int n) o Sleeps the thread for given time in milliseconds and nanoseconds  Thread.yield() o Pauses currently executing thread and put at last in the runnable queue
  • 22.
    www.SunilOS.com 22 Daemon Threads Daemon threads are supporting and background threads  It provides services to normal threads  Garbage Collector is a Daemon thread.  t.setDaemon(true) Daemon Thread Normal Thread
  • 23.
    Usage | multiuser system www.SunilOS.com 23 Web Application Database
  • 24.
  • 25.
    www.SunilOS.com 25 Race Condition Threads of a process can share common memory area  When two threads simultaneously try to access and modify an object, it is called race-condition  The result of a program is affected by the order in which threads are allocated CPU time and executed
  • 26.
    www.SunilOS.com 26 Deposit inthe Account Account Balance = 1000 Balance = 2000 getBalance():1000 setBalance(2000) setBalance(2000) getBalance():1000 getBalance() CPU getBalance() setBalance() setBalance() User1 User 2 Deposit Deposit
  • 27.
    www.SunilOS.com 27 Synchronized access Account Balance= 1000 Balance = 3000 getBalance():1000 setBalance(2000) setBalance(3000) getBalance():2000 User1 User 2 Deposit Deposit getBalance() CPU locked setBalance() setBalance() getBalance()
  • 28.
    www.SunilOS.com 28 Account 1. publicclass Account { 2. private int balance = 0; 3. public int getBalance() { 4. try { 5. Thread.sleep(200); 6. } catch (InterruptedException e) {} 7. return balance; 8. } 9. public void setBalance(int balance) { 10. try { 11. Thread.sleep(200); 12. } catch (InterruptedException e) {} 13. this.balance = balance; 14. } 15.
  • 29.
    www.SunilOS.com 29 Account 1. publicsynchronized void deposit(String msg, int amt) { 2. int bal = getBalance(); 3. bal = bal + amt; 4. setBalance(bal); 5. System.out.println(msg + " new balance " + bal); 6. } 7. }
  • 30.
    www.SunilOS.com 30 RacingCondThread public classRacingCondThread extends Thread { public static Account data = new Account(); String name = null; public RacingCondThread(String name) { this.name = name; } public void run() { for(int i=0;i<5;i++){ data.deposit(name, 1000); } }
  • 31.
    www.SunilOS.com 31 TestRacingCondThread public staticvoid main(String[] args) { RacingCondThread t1 = new RacingCondThread(“Ram"); RacingCondThread t2 = new RacingCondThread(“Shyam"); t1.start(); t2.start(); }
  • 32.
    Output  void deposit(..) oRam balance 1000 o Shyam balance 1000 o Ram balance 2000 o Shyam balance 2000 o Shyam balance 3000 o Ram balance 3000 o Shyam balance 4000 o Ram balance 4000 o Shyam balance 5000 o Ram balance 5000  synchronized void deposit(..) o Ram balance 1000 o Ram balance 2000 o Ram balance 3000 o Ram balance 4000 o Ram balance 5000 o Shyam balance 6000 o Shyam balance 7000 o Shyam balance 8000 o Shyam balance 9000 o Shyam balance 10000 www.SunilOS.com 32
  • 33.
    www.SunilOS.com 33 Synchronization types Method publicsynchronized void deposit(String message, int amount) {….} Block public void deposit(String message, int amount) { synchronized (this){ int bal = getBalance() + amount; setBalance(bal); } System.out.println(message + " Now Bal is " + bal); }
  • 34.
    www.SunilOS.com 34 Monitors /Locks  It is a lock or token of an object  The thread has lock, can access object  Other threads will be in waiting queue  One object has two monitors or tokens o One for instance methods, called Object Monitor o Second for static methods, called Class Monitor
  • 35.
    www.SunilOS.com 35 Monitor Keys StaticSync Methods x z y Instance Sync Methods a c b Thread1 Thread2 x() Class Monitor y() a() Object Monitor b() CLASS
  • 36.
    Disclaimer This is aneducational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 36
  • 37.

Editor's Notes