Threads in Java
Threads in Java
Multithreading:
A thread is a single sequence of execution within a program refers to multiple threads of control within a single program each program can run multiple threads of control within it, e.g., Chat Client
Motivation
If we are designing a software for chatting, we need to execute a program, in background, that will read message from the server. And another program that will help you to type new message using some GUI. The important thing is that both of these programs should run simultaneously, which is only possible if your system contains multiple processors.
GC
Application Thread
When we execute an application:
1. The JVM creates a Thread object whose task is defined by the main() method 2. The JVM starts the thread
However, all threads see the same dynamic memory, i.e., heap (are there variables on the heap?) Two different threads can act on the same object and same static fields concurrently
6
Creating Threads
There are two ways to create our own
Thread object
1. Implementing the Runnable interface 2. Subclassing the Thread class and instantiating a new object of that class
Thread class
In java, we create threads by using Thread
t.start();
By creating a new Thread object, we can
But there is one problem. The thread doesnt actually do anything. So it will dies virtually the instant its born. And when the thread dies, its new stack disappears.
Runnable interface
Runnable is an interface defined in java.lang package. The object of a class, which will implement Runnable interface, will be a job for thread. class MyRunnable implements Runnable { public void run() { } }
By simply creating an object of Thread class does not create a new thread. The invocation of start() method creates a new thread of execution, means a separate call stack by invoking the run() method.
main()
Main thread
start() main()
Main thread
run()
new thread
}
13
14
public class CustomThread extends Thread { public CustomThread() { } // Override the run method in Runnable public void run() { // Tell system how to perform this task } }
15
public class Client { public void someMethod() { CustomThread thread1 = new CustomThread(); thread1.start(); CustomThread thread2 = new CustomThread(); thread2.start(); } }
16
This approach is, however, not recommended, because it mixes the task and the mechanism of running the task. Separating the task from the thread is a preferred design.
Moreover, logically, if we think Thread class as a worker, then we should not extend it until we need a more specific worker.
17
Thread Methods
void start() Creates a new thread and makes it runnable This method can be called only once void run() The new thread begins its life inside this method void stop() (deprecated)
Thread Methods
void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute Allow only threads of the same priority to run Does not release any lock void sleep(int m) The thread sleeps for m milliseconds Does not release any lock
19
join() method
The join() method tells the current thread to
20
21
sleep method
Show sleep demo in netbeans
22
Thread Priority
Every thread has a priority When a thread is created, it inherits the priority of the thread that created it
23
25
Scheduling Threads
start()
Ready queue
Newly created Thread objects Currently executed thread I/O operation completes
Waiting for I/O operation to be Waiting to be notified Sleeping Waiting to enter a synchronized
completed
section
26
thread.start();
27
Example
public class PrintThread1 extends Thread { String name; public PrintThread1(String name) { this.name = name; } public void run() { for (int i=1; i<100 ; i++) {
try {
sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) { } System.out.print(name);
}
}
28
Example (cont)
public static void main(String args[]) { PrintThread1 a = new PrintThread1("*"); PrintThread1 b = new PrintThread1("-"); a.start(); b.start(); } }
29
Daemon Threads
Daemon threads are background threads, that provide services to other threads, e.g., the garbage collection thread The Java VM will not exit if non-Daemon threads are executing The Java VM will exit if only Daemon threads are executing
31
Concurrency
An object in a program can be changed by
32
Synchronized methods
The synchronized is a keyword used in Java
33
Monitors
Each object has a monitor that is a token
Monitor (cont.)
Entering a monitor is also referred to as locking the monitor, or acquiring ownership of the monitor If a thread A tries to acquire ownership of a monitor and a different thread has already entered the monitor, the current thread (A) must wait until the other thread leaves the monitor
35
object.
Goal of synchronization is to protect data. So
36
Critical Section
The synchronized methods define critical
sections
Execution of critical sections is mutually
exclusive.
37
Example
public class BankAccount { private float balance; public synchronized void deposit(float amount){ balance += amount; } public synchronized void withdraw(float amount){ balance -= amount; } }
38
t3
t2
t1
Critical Sections
deposit()
Bank Account
39
public class Test { public synchronized void a() { b(); System.out.println(I am at a); } public synchronized void b() { System.out.println(I am at b); } }
40
41
Synchronized Statements
A monitor can be assigned to a block:
synchronized(object) { some-code }
It can also be used to monitor access to a data element that is not an object, e.g., array:
void addName(String name) { synchronized(this) { lastName = name;
//these two statements will execute as an atomic operation
nameCount++;
} nameList.add(name);}
42
}
}
43
}
}
44
Example
public class MyPrinter { public MyPrinter() {} public synchronized void printName(String name) { for (int i=1; i<100 ; i++) { try { Thread.sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) {} System.out.print(name); }
}
}
45
Example
public class PrintThread2 extends Thread { String name; MyPrinter printer; public PrintThread2(String name, MyPrinter printer){ this.name = name; this.printer = printer; } public void run() { printer.printName(name); } }
46
Example (cont)
public class ThreadsTest2 { public static void main(String args[]) { MyPrinter myPrinter = new MyPrinter(); PrintThread2 a = new PrintThread2("*, printer); PrintThread2 b = new PrintThread2("-, printer);
47
Deadlock Example
public class BankAccount { private float balance;
public class MoneyTransfer implements Runnable { private BankAccount from, to; private float amount; public MoneyTransfer( BankAccount from, BankAccount to, float amount){ this.from = from; this.to = to; this.amount = amount; } public void run() { source.transfer(amount, target); }
49
// At one place Runnable transaction1 = new MoneyTransfer(aliceAccount, bobAccount, 1200); Thread t1 = new Thread(transaction1); t1.start();
// At another place Runnable transaction2 = new MoneyTransfer(bobAccount, aliceAccount, 700); Thread t2 = new Thread(transaction2); t2.start();
50
Deadlocks
t1 t2
aliceAccount
bobAccount
transfer() withdraw() deposit()
transfer()
withdraw() deposit()
51
Thread Synchronization
We need to synchronized between
52
53
54
force it to be rescheduled
However, wait() is not automatically put back into the scheduler queue
notify() must be called in order to get a thread back into the schedulers queue The objects monitor must be reacquired before the threads run can continue What is the difference between wait and sleep?56
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
57
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
58
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
59
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
60
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
61
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
62
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
63
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
64
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
65
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
66
Wait/Notify Sequence
Lock Object
Consumer Thread
Producer Thread
67