OOP-ch07-Thread in Java
OOP-ch07-Thread in Java
Thread in Java
InterruptedException
Example
class TestJoin extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoin t1 = new TestJoin();
TestJoin t2 = new TestJoin();
TestJoin t3 = new TestJoin();
t1.start();
try {
t1.join();
} catch (Exception e) {
System.out.println(e);
}
t2.start();
t3.start();
}
}
public static void main(String args[]){
TestJoin t1 = new TestJoin();
TestJoin t2 = new TestJoin();
TestJoin t3 = new TestJoin();
t1.start();
try {
t1.join(1500);
} catch (Exception e) {
System.out.println(e);
}
t2.start();
t3.start();
}
}
Thread Synchronization
◼ Thread synchronization is the concurrent execution of two or more
threads that share critical resources. Threads should be synchronized
to avoid critical resource use conflicts. Otherwise, conflicts may
arise when parallel-running threads attempt to modify a common
variable at the same time.
◼ Let’s suppose we have an online banking system, where people can
log in and access their account information. Whenever someone logs
in to their account online, they receive a separate and unique thread
so that different bank account holders can access the central system
simultaneously.
public class BankAccount {
int accountNumber;
double accountBalance;
public boolean transfer (double amount){
double newAccountBalance;
if( amount > accountBalance) {
return false; }
else {
newAccountBalance = accountBalance -
amount;
accountBalance = newAccountBalance;
return true;
}
}
public boolean deposit(double amount) {
double newAccountBalance;
if( amount < 0.0) {
return false;
} else {
newAccountBalance = accountBalance +
amount;
accountBalance = newAccountBalance;
return true;
}
}
A race condition
◼ Let’s say that there’s a husband and wife - Jack and Jill - who
share a joint account. They currently have $1,000 in their
account. They both log in to their online bank account at the
same time, but from different locations.
◼ They both decide to deposit $200 each into their account at the
same time.
◼ So, the total account balance after these 2 deposits should be
$1,000 + ($200 * 2), which equals $1,400.
◼ Let’s say Jill’s transaction goes through first, but Jill's thread of
execution is switched out
Synchronization fixes race conditions
◼ In the code below, all we do is add the synchronized
keyword to the transfer and deposit methods
◼ public synchronized boolean transfer (double amount){}
◼ public synchronized boolean deposit(double amount){}
◼ This means that only one thread can execute those
functions at a time
public class SynMethod {
public static void print(String s){
String
name=Thread.currentThread().getName();
System.out.println(name+" - "+s);
}
public void takeaPen(){
print("Take a pen");
print("be writing");
try{
Thread.sleep(2000);
}catch(Exception e){
e.fillInStackTrace();
}
print("finish writing!");
}
public static void main(String[] agrs){
final SynMethod bb=new SynMethod();
Runnable runA = new Runnable(){
public void run(){
bb.takeaPen();
}};
Thread threadA = new
Thread(runA,"threadA");
threadA.start();
try{
Thread.sleep(200);
}catch(Exception e){
e.fillInStackTrace();}
Runnable runB = new Runnable(){
public void run(){
bb.takeaPen();
}
};
Thread threadB = new
Thread(runB,"threadB");
threadB.start();
}
}
wait(), notify() and notifyAll()
◼ Multithreading replaces event loop programming by dividing
your tasks into discrete and logical units.
◼ Three methods: wait( ), notify( ), and notifyAll( ), these
methods are implemented as final methods in Object and can
be called only from within a synchronized method.
◼ final void wait( ) throws InterruptedException
◼ final void notify( )
◼ final void notifyAll( )
The rules for using three methods
◼ wait( ) tells the calling thread to give up the monitor and go to
sleep until some other
thread enters the same monitor and calls notify( ).
◼ notify( ) wakes up the first thread that called wait( ) on the
same object.
◼ notifyAll( ) wakes up all the threads that called wait( ) on the
same object. The
highest priority thread will run first.
The sample program incorrectly implements
(usenotify)
◼ It consists of four classes: Q, the queue that you're trying to
synchronize; Producer, the threaded object that is
producing queue entries; Consumer, the threaded object
that is consuming queue entries; and PC, the tiny class that
creates the single Q, Producer, and Consumer.
Class Q
class Q {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
Class Producer/ Consumer
class Producer class Consumer
implements Runnable { implements Runnable
Q q; {
Producer(Q q) { Q q;
this.q = q; Consumer(Q q) {
new Thread(this, this.q = q;
"Producer").start(); new Thread(this,
} "Consumer").start();
public void run() { }
int i = 0; public void run() {
while(true) { while(true) {
q.put(i++); q.get();
}
}
} }
} }
Class PC
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Running (PC)
◼ Although the put( ) and get( ) methods on Q are synchronized, nothing stops
the producer from overrunning the consumer, nor will anything stop the
consumer from consuming the same queue value twice.
A correct implementation
◼ The proper way to write this program in Java is to use wait( )
and notify( ) to signal in both directions
◼ Inside get( ), wait( ) is called.
◼ After the data has been obtained, get( ) calls notify( ).
Inside get( )
synchronized int get() {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException
caught");}
System.out.println("Got: " + n);
return n;}
Inside put( )
synchronized void put(int n) {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException
caught");}
this.n = n;
System.out.println("Put: " + n);}
Running (PCFixed)
Deadlock
◼ Deadlock describes a
situation where two or
more threads are
blocked forever, waiting
for each other → All
threads in a group halt.
◼ When does deadlock
occur?
◼ There exists a circular Nothing can ensure
wait the lock that is held that DEADLOCK do
not occur.
by other thread.
Deadlock Demo.
The Philosophers Problem
Wait-Notify
Mechanism, a way
helps preventing
deadlocks
Deadlock!
3 classes
Thread table