You are on page 1of 8

Programming Java

Multithreaded Programming

Incheon Paik

1 Computer Industry Lab.


Java

Contents

„ An Overview of Threads
„ Creating Threads
„ Synchronization
„ Deadlock
„ Thread Communication

2 Computer Industry Lab.


Java
An Overview of Threads
Threads

ƒWhat is a Thread?
•A sequence of execution within a process
•A Lightweight process
•JVM manages and schedules threads
•Possible States:
(1) new (2) ready (3) running (4) waiting (5) dead

3 Computer Industry Lab.


Java

An Overview of Threads
Threads

ƒThread life cycle

Dead

Sleep,wait,I/O

New Ready Running Waiting

4 Computer Industry Lab.


Java
Creating Threads
Extending Thread Class Runnable Interface
class RunnableY implements Runnable {
class ThreadX extends Thread {
public void run() {
public void run() { // process Threads
// process Threads }
}
} }

Starting a Thread Starting a Thread


ThreadX tx = new ThreadX(); RunnableY ry = new RunnableY();
tx.start(); Thread ty = new Thread(ry);
tx.start();

run() method Thread Constructor


public void run(); Thread()
Thread(Runnable r)
Thread(Runnable r, string s)
Thread(String s)

5 Computer Industry Lab.


Java

Methods in a Thread
Static Methods of the Thread Class Instance Methods of Thread

•static Tread currentThread() •String getName()


•static void sleep(long msec) throws int •int getPriority()
erruptedException
•boolean isAlive()
•static void sleep(long msec, int nsec) t
hrows InterruptedException •void join() throws InterrupteException
•static void yield() •void join(long msec) throws Interrupte
dException
•void join(long msec, int nsec) throws I
nterruptedException
•void run()
•void setName(String s)
Refer to the URL •void setPriority(int p)
http://java.sun.com/j2se/1.4.2/ •void start()
docs/api/java/lang/Thread.html
•String toString()

6 Computer Industry Lab.


Java
Creating Threads
class ThreadX extends Thread {
Result :
public void run() {
try {
Hello
while(true) { … 2 seconds
Thread.sleep(2000); Hello
System.out.println("Hello");
}
}
catch(InterruptedException ex) {
ex.printStackTrace();
} Body of run method
}
}

class ThreadDemo1 {
public static void main(String args[]) {
ThreadX tx = new ThreadX();
tx.start();
}
}

7 Computer Industry Lab.


Java

Creating Threads
class JoinDemo1 {
class ThreadM extends Thread {
public static void main(String args[]) {
public void run() {
try {
ThreadM tm = new ThreadM();
for (int i = 0; i < 10; i++) {
tm.start();
Thread.sleep(1000);
ThreadN tn = new ThreadN();
System.out.println("ThreadM");
tn.start();
}
try { join() method:
}
tm.join(); Waits for this thread to die.
catch (InterruptedException ex) {
tn.join();
ex.printStackTrace();
System.out.println("Both threads have
} finished");
} }
} catch (Exception e) {
e.printStackTrace();
class ThreadN extends Thread { }
public void run() { }
try { }
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
System.out.println("ThreadN");
}
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
8 Computer Industry Lab.
Java
Synchronization
Thread Scheduling
Synchronized Block

Synchronized (obj) {
// Process Block
}

If a thread invokes a
synchronized method, the
object will be locked. If
other threads invoke the
synchronized method of
that object, the threads
will be blocked.

Data Corruption!
Need Synchronization

9 Computer Industry Lab.


Java

Locking Objects with Synchronized Methods


thread 1 thread 2 thread 3

run() { run() {
run() {
obj1.method3(); obj2.method3();
obj1.method2();
obj1.method1(); obj2.method2();
}
obj2.method1(); }
}

1
2 4 5
3 OK. 6
method1()
Not busy
obj 1 obj 2
synchronized synchronized
method1() method1()
No!
synchronized synchronized
Not while method2()
method2() for obj1 is executing method2()
OK.
method2() method3() method3()
Not busy Always OK. No! Always OK.
Not while method1()
for obj2 is executing
10 Computer Industry Lab.
Java
Synchronization
class Account { class BankDemo {
private int balance = 0; private final static int NUMCUSTOMERS = 10;

synchronized void deposit(int amount) { public static void main(String args[]) {


balance += amount;
} // Create Account
Account account = new Account();
int getBalance() {
return balance; //Create and start customer threads
} Customer customers[] = new
} Customer[NUMCUSTOMERS];
for (int i = 0; i < NUMCUSTOMERS; i++) {
class Customer extends Thread { customers[i] = new Customer(account);
Account account; customers[i].start();
}
Customer(Account account) {
this.account = account; //Wait for customer threads to complete
} for (int i = 0; i < NUMCUSTOMERS; i++) {
try {
public void run() { customers[i].join();
try { }
for (int i = 0; i < 100000; i++) { catch(InterruptedException e) {
account.deposit(10); e.printStackTrace();
} }
} }
catch(Exception e) { Result :
e.printStackTrace(); // Display Account balance
} 10,000,000 System.out.println(account.getBalance());
} }
} }
11 Computer Industry Lab.
Java

Deadlock
class A { public void run() { // Create threads
B b; for (int i = 0; i < 100000; i++) Thread1 t1 = new Thread1(a);
a.a1(); Thread2 t2 = new Thread2(b);
synchronized void a1() { } t1.start();
System.out.println("Starting a1"); t2.start();
b.b2(); }
} // Wait for threads to complete
class Thread2 extends Thread { try {
synchronized void a2() { B b; t1.join();
System.out.println("Starting a2"); t2.join();
} Thread2(B b) { }
} this.b = b; catch(Exception e) {
} e.printStackTrace();
class B { }
A a;
public void run() { //Display Message
synchronized void b1() { for (int i = 0; i < 100000; i++) System.out.println("Done!");
System.out.println("Starting b1"); b.b1(); }
a.a2(); } }
} }
Condition for Deadlock:
synchronized void b2() { class DeadlockDemo { - Mutual Exclusion - Hold & Wait
System.out.println("Starting b2");
} - No-preemption - Circular Wait
public static void main(String args[])
} {

class Thread1 extends Thread { Result :


// Create Objects
A a; Starting a1
A a = new A();
B b = new B(); Starting b2
Thread1(A a) { Starting a1
this.a = a; a.b = b;
} b.a = a; Starting b2
……….
12 Computer Industry Lab.
Java
Thread Communication
wait() Method Not Runnable status
void wait() throws InterruptedException
The wait() method allows a thread that is
void wait(long msec) throws InterruptedExc executing a synchronized method or statement
eption
block on that object to release the lock and wait
void wait(long msec, int nsec) throws Interr
uptedException
for a notification from another thread.

The notify() method allows a thread that is


Notify Method executing a synchronized method or statement
block to notify another thread that is waiting for a
void notify() lock on this object.

notifyAll() Method
void notifyAll()

13 Computer Industry Lab.


Java

Producer & Consumer Example


class Producer extends Thread { class Queue {
int element = array[r++];
Queue queue; private final static int SIZE = 10;
if (r >= SIZE)
int array[] = new int[SIZE];
r = 0;
Producer(Queue queue) { int r = 0;
--count;
this.queue = queue; int w = 0;
notifyAll();
} int count = 0;
return element;
synchronized void add(int i) {
}
public void run() { while(count == SIZE) {
}
int i = 0; try {
while(true) { wait();
class ProducerConsumers {
queue.add(i++); }
public static void main(String args[]) {
} catch(InterruptedException ie) {
} ie.printStackTrace(); Queue queue = new Queue();
} System.exit(0); new Producer(queue).start();
} new Consumer("ConsumerA",
class Consumer extends Thread { } queue).start();
String str; array[w++] = i; new Consumer("ConsumerB",
Queue queue; if (w >= SIZE) queue).start();
w = 0; new Consumer("ConsumerC",
queue).start();
{ Consumer(String str, Queue queue) ++count;
}
this.str = str; notifyAll();
} }
this.queue = queue;
} synchronized int remove() {
while(count == 0) {
public void run() { try {
while(true) { wait();
System.out.println(str + ": " + }
queue.remove()); catch(InterruptedException ie) {
} ie.printStackTrace();
} System.exit(0);
} }
}

14 Computer Industry Lab.


Java
Exercise
„ Step 1 (Bank Example 1)
Slide 9
You can use several ways to change the result of step 1.
As a way of those, I recommend you to use the synchronized statement block.

„ Synchronized statement block


- We can specify a statement or a block of code in a program as synchronzied.

“Form”
synchronized(theObject) {
// statement block
}

No other statements or statements blocks in the program that are synchronized on the object can
execute while this statement is executing.

15 Computer Industry Lab.


Java

Exercise

„ Step 2 (Bank Example 2)


Slides 9 - 11
Remember the synchronized statement block and method

„ Step 3 (Producer and Consumer 1)


Slides 9 - 14

16 Computer Industry Lab.


Java

You might also like