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.wait.I/O New Ready Running Waiting 4 Computer Industry Lab. Java . Java An Overview of Threads Threads ƒThread life cycle Dead Sleep.

Thread ty = new Thread(ry).com/j2se/1. Thread() Thread(Runnable r) Thread(Runnable r. RunnableY ry = new RunnableY(). 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().start().2/ •void start() docs/api/java/lang/Thread. int nsec) t hrows InterruptedException •void join() throws InterrupteException •static void yield() •void join(long msec) throws Interrupte dException •void join(long msec. 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. run() method Thread Constructor public void run().4. tx. int nsec) throws I nterruptedException •void run() •void setName(String s) Refer to the URL •void setPriority(int p) http://java.sun. Java . tx.html •String toString() 6 Computer Industry Lab.start().

println("Hello"). tx. tn. i++) { Thread. class ThreadN extends Thread { } public void run() { } try { } for (int i = 0. } } } 8 Computer Industry Lab. Hello System.start().join(). Thread. i < 20. } } catch(InterruptedException ex) { ex.println("Both threads have } finished"). } try { join() method: } tm. } } 7 Computer Industry Lab.join().out. } } } catch (Exception e) { e.start().out. System.sleep(2000). Java . ThreadN tn = new ThreadN().println("ThreadM"). } Body of run method } } class ThreadDemo1 { public static void main(String args[]) { ThreadX tx = new ThreadX(). catch (InterruptedException ex) { tn. i < 10.sleep(2000). Waits for this thread to die.printStackTrace().sleep(1000).printStackTrace().printStackTrace(). System. Java Creating Threads class JoinDemo1 { class ThreadM extends Thread { public static void main(String args[]) { public void run() { try { ThreadM tm = new ThreadM(). Creating Threads class ThreadX extends Thread { Result : public void run() { try { Hello while(true) { … 2 seconds Thread. i++) { tm. ex. System.out.start().println("ThreadN").out. } } catch(InterruptedException ex) { ex. for (int i = 0.printStackTrace().

obj2. Data Corruption! Need Synchronization 9 Computer Industry Lab.method3().method2(). Not while method1() for obj2 is executing 10 Computer Industry Lab. } } 1 2 4 5 3 OK.method1(). If other threads invoke the synchronized method of that object. the threads will be blocked. Java . } obj2. Java Locking Objects with Synchronized Methods thread 1 thread 2 thread 3 run() { run() { run() { obj1. obj2. No! Always OK. obj1. Synchronization Thread Scheduling Synchronized Block Synchronized (obj) { // Process Block } If a thread invokes a synchronized method. the object will be locked. 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.method1().method2().method3(). obj1.

b.println("Starting a1"). } } } } 11 Computer Industry Lab. e. //Wait for customer threads to complete } for (int i = 0.000.b = b.a = a. i < NUMCUSTOMERS.out.println("Starting b1"). } Thread2(B b) { } } this.000 System.out. i++) { class Customer extends Thread { customers[i] = new Customer(account). i < 100000.start().b1().Mutual Exclusion . } b. t2. } } // Wait for threads to complete class Thread2 extends Thread { try { synchronized void a2() { B b. a. Java Deadlock class A { public void run() { // Create threads B b.out.out. i++) { try { public void run() { customers[i].join(). public void run() { //Display Message synchronized void b1() { for (int i = 0. } a.No-preemption . for (int i = 0. 12 Computer Industry Lab. Account account. i < 100000.a2().deposit(10).start(). i++) Thread1 t1 = new Thread1(a). //Create and start customer threads } Customer customers[] = new } Customer[NUMCUSTOMERS].out.getBalance()). try { } for (int i = 0. System.println(account.account = account. a.println("Done!"). catch(Exception e) { } e.Circular Wait public static void main(String args[]) } { class Thread1 extends Thread { Result : // Create Objects A a. B b = new B().a1().Hold & Wait System.printStackTrace(). } } } } Condition for Deadlock: synchronized void b2() { class DeadlockDemo { . i < NUMCUSTOMERS. i++) { catch(InterruptedException e) { account. private final static int NUMCUSTOMERS = 10. Thread2 t2 = new Thread2(b). } } } } catch(Exception e) { Result : e. t2. System. System.start().printStackTrace(). } .printStackTrace().join().b2(). customers[i]. i < 100000. Starting b2 ………. t1.join(). synchronized void a1() { } t1.println("Starting a2"). } Customer(Account account) { this.b = b. Java .println("Starting b2"). synchronized void deposit(int amount) { public static void main(String args[]) { balance += amount. b.out. class B { } A a. for (int i = 0.a = a. Starting b2 Thread1(A a) { Starting a1 this. i++) System. } // Create Account Account account = new Account(). int getBalance() { return balance. Synchronization class Account { class BankDemo { private int balance = 0. Starting a1 A a = new A(). // Display Account balance } 10.

int nsec) throws Interr uptedException for a notification from another thread.printStackTrace(). Queue queue) ++count. String str. synchronized void add(int i) { } public void run() { while(count == SIZE) { } int i = 0. 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. Producer(Queue queue) { int r = 0. 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. Java Producer & Consumer Example class Producer extends Thread { class Queue { int element = array[r++]. } } } 14 Computer Industry Lab. return element. catch(InterruptedException ie) { } ie. notifyAll(). this. } System.exit(0). array[w++] = i.queue = queue. try { while(true) { wait(). } new Consumer("ConsumerA". w = 0. } } this. } int count = 0.start(). class Consumer extends Thread { } queue). notifyAll(). new Producer(queue).str = str. Queue queue.remove()).out. Java . r = 0.println(str + ": " + } queue. notifyAll() Method void notifyAll() 13 Computer Industry Lab. } this. int w = 0.queue = queue. if (r >= SIZE) int array[] = new int[SIZE]. --count. Queue queue.printStackTrace(). new Consumer("ConsumerB". { Consumer(String str. } System. } public static void main(String args[]) { } catch(InterruptedException ie) { } ie. Queue queue = new Queue(). class ProducerConsumers { queue. queue).add(i++). } synchronized int remove() { while(count == 0) { public void run() { try { while(true) { wait().start(). private final static int SIZE = 10. System. new Consumer("ConsumerC".exit(0).start(). if (w >= SIZE) queue).start().

As a way of those. 15 Computer Industry Lab.We can specify a statement or a block of code in a program as synchronzied.11 Remember the synchronized statement block and method „ Step 3 (Producer and Consumer 1) Slides 9 .14 16 Computer Industry Lab. I recommend you to use the synchronized statement block. „ Synchronized statement block . “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. Java . Exercise „ Step 1 (Bank Example 1) Slide 9 You can use several ways to change the result of step 1. Java Exercise „ Step 2 (Bank Example 2) Slides 9 .