• No results found

Multithreaded programming.pdf

N/A
N/A
Protected

Academic year: 2020

Share "Multithreaded programming.pdf"

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

1

1 Java

Java Computer Industry Lab.Computer Industry Lab.

Programming Java

Multithreaded Programming

Incheon Paik

2

2 Java

Java Computer Industry Lab.Computer Industry Lab.

Contents

Contents

„

An Overview of Threads

„

Creating Threads

„

Synchronization

„

Deadlock

(2)

3

3 Java

Java Computer Industry Lab.Computer Industry Lab.

An

An

Overview of Thread

Overview of Thread

s

s

ƒ

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

4

4 Java

Java Computer Industry Lab.Computer Industry Lab.

An

An

Overview of Thread

Overview of Thread

s

s

ƒ

Thread life cycle

Ready

New

Running

Waiting

Dead

(3)

5

5 Java

Java Computer Industry Lab.Computer Industry Lab.

Creating Thread

Creating Thread

s

s

class ThreadX extends Thread { public void run() {

// process Threads }

}

Extending Thread Class

ThreadX tx = new ThreadX(); tx.start();

Starting a Thread

public void run();

run() method

class RunnableY implements Runnable { public void run() {

// process Threads }

}

Runnable Interface

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

Starting a Thread

Thread() Thread(Runnable r) Thread(Runnable r, string s) Thread(String s)

Thread Constructor

6

6 Java

Java Computer Industry Lab.Computer Industry Lab.

Methods in

Methods in

a

a

Thread

Thread

static Tread currentThread()

static void sleep(long msec) throws int

erruptedException

static void sleep(long msec, int nsec) t

hrows InterruptedException

static void yield()

Static Methods of the Thread Class

String getName()

int getPriority()

boolean isAlive()

void join() throws InterrupteException

void join(long msec) throws Interrupte

dException

void join(long msec, int nsec) throws I

nterruptedException

void run()

void setName(String s)

void setPriority(int p)

void start()

String toString()

Instance Methods of Thread

Refer to the URL

(4)

7

7 Java

Java Computer Industry Lab.Computer Industry Lab.

Creating Thread

Creating Thread

s

s

class ThreadX extends Thread {

public void run() { try {

while(true) { Thread.sleep(2000); System.out.println("Hello"); }

}

catch(InterruptedException ex) { ex.printStackTrace(); }

} }

class ThreadDemo1 {

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

} }

Result : Hello

…2 seconds

Hello

Body of run method

8

8 Java

Java Computer Industry Lab.Computer Industry Lab.

Creating Thread

Creating Thread

s

s

class ThreadM extends Thread { public void run() { try {

for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("ThreadM"); }

}

catch (InterruptedException ex) { ex.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(); }

} }

join() method:

Waits for this thread to die. class JoinDemo1 {

public static void main(String args[]) {

ThreadM tm = new ThreadM(); tm.start();

ThreadN tn = new ThreadN(); tn.start();

try { tm.join(); tn.join();

System.out.println("Both threads have finished");

}

catch (Exception e) { e.printStackTrace(); }

(5)

9

9 Java

Java Computer Industry Lab.Computer Industry Lab.

Synchronization

Synchronization

Thread Scheduling

Data Corruption! Need Synchronization

Synchronized (obj) {

// Process Block

}

Synchronized 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.

10

10 Java

Java Computer Industry Lab.Computer Industry Lab.

Locking Objects with

Locking Objects with

Synchroniz

Synchroniz

ed Methods

ed Methods

run() { obj1.method2(); }

thread 1

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

thread 2

synchronized method1() synchronized

method2() method3() obj 1

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

thread 3

synchronized method1() synchronized

method2() method3() obj 2

1

2

3 4 6 5

OK. method2()

Not busy AlwaysOK.

No!

Not while method2() for obj1 is executing

No!

Not while method1() for obj2 is executing OK.

method1() Not busy

(6)

11

11 Java

Java Computer Industry Lab.Computer Industry Lab.

Synchronization

Synchronization

class Account { private int balance = 0;

synchronized void deposit(int amount) { balance += amount;

}

int getBalance() { return balance; }

}

class Customer extends Thread { Account account;

Customer(Account account) { this.account = account; }

public void run() { try {

for (int i = 0; i < 100000; i++) { account.deposit(10); }

}

catch(Exception e) { e.printStackTrace(); } } } Result : 10,000,000

class BankDemo {

private final static int NUMCUSTOMERS = 10;

public static void main(String args[]) {

// Create Account

Account account = new Account();

//Create and start customer threads Customer customers[] = new Customer[NUMCUSTOMERS];

for (int i = 0; i < NUMCUSTOMERS; i++) { customers[i] = new Customer(account); customers[i].start();

}

//Wait for customer threads to complete for (int i = 0; i < NUMCUSTOMERS; i++) {

try {

customers[i].join(); }

catch(InterruptedException e) { e.printStackTrace(); }

}

// Display Account balance

System.out.println(account.getBalance()); } } 12 12 Java

Java Computer Industry Lab.Computer Industry Lab.

Deadlock

Deadlock

class A { B b;

synchronized void a1() { System.out.println("Starting a1"); b.b2();

}

synchronized void a2() { System.out.println("Starting a2"); }

}

class B { A a;

synchronized void b1() { System.out.println("Starting b1"); a.a2();

}

synchronized void b2() { System.out.println("Starting b2"); }

}

class Thread1 extends Thread { A a;

Thread1(A a) { this.a = a; } Result : Starting a1 Starting b2 Starting a1 Starting b2 ………. public void run() {

for (int i = 0; i < 100000; i++) a.a1();

} }

class Thread2 extends Thread { B b;

Thread2(B b) { this.b = b; }

public void run() {

for (int i = 0; i < 100000; i++) b.b1();

} }

class DeadlockDemo {

public static void main(String args[]) {

// Create Objects A a = new A(); B b = new B(); a.b = b; b.a = a;

// Create threads

Thread1 t1 = new Thread1(a); Thread2 t2 = new Thread2(b); t1.start();

t2.start();

// Wait for threads to complete try {

t1.join(); t2.join(); }

catch(Exception e) { e.printStackTrace(); } //Display Message System.out.println("Done!"); } }

(7)

13

13 Java

Java Computer Industry Lab.Computer Industry Lab.

Thread Communication

Thread Communication

void wait() throws InterruptedException void wait(long msec) throws InterruptedExc eption

void wait(long msec, int nsec) throws Interr uptedException

wait() Method

void notify()

Notify Method

void notifyAll()

notifyAll() Method

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

The wait() method allows a thread that is executing a synchronized method or statement block on that object to release the lockand wait for a notificationfrom another thread.

Not Runnable status

14

14 Java

Java Computer Industry Lab.Computer Industry Lab.

Producer & Consumer Example

Producer & Consumer Example

class Producer extends Thread { Queue queue;

Producer(Queue queue) { this.queue = queue; }

public void run() { int i = 0; while(true) {

queue.add(i++); }

} }

class Consumer extends Thread { String str;

Queue queue;

Consumer(String str, Queue queue) {

this.str = str; this.queue = queue; }

public void run() { while(true) {

System.out.println(str + ": " + queue.remove());

} } }

class Queue {

private final static int SIZE = 10; int array[] = new int[SIZE]; int r = 0;

int w = 0; int count = 0;

synchronized void add(int i) { while(count == SIZE) {

try { wait(); }

catch(InterruptedException ie) { ie.printStackTrace(); System.exit(0); }

}

array[w++] = i; if (w >= SIZE)

w = 0; ++count; notifyAll(); }

synchronized int remove() { while(count == 0) {

try { wait(); }

catch(InterruptedException ie) { ie.printStackTrace(); System.exit(0); }

}

int element = array[r++]; if (r >= SIZE)

r = 0; --count; notifyAll(); return element; }

}

class ProducerConsumers {

(8)

15

15 Java

Java Computer Industry Lab.Computer Industry Lab.

Exercise

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.

16

16 Java

Java Computer Industry Lab.Computer Industry Lab.

Exercise

Exercise

„

Step 2 (Bank Example 2)

Slides 9 - 11

Remember the synchronized statement block and method

References

Related documents

This product is not authorized for use in equipment where a higher safety standard and reliability standard is especially required or where a failure of the product is

Synchronized Queue 1 1 Entrance Queue synchronized m1() synchronized m2() Thread 1 m2() m1() Thread 2 A Java Monitor Object &lt;&lt;contains&gt;&gt; &lt;&lt;contains&gt;&gt; Wait

Vantage Safety offers repair and maintenance services for a wide variety of gas detection and monitoring devices. We operate a 10,000-square-foot repair facility in

Favor you leave and sample policy employees use their job application for absence may take family and produce emails waste company it discusses email etiquette Deviation from

The objective of this research is to develop a prototype student advising expert system that assists the students of Information Systems (IS) major in selecting their

SRPF = School Risk &amp; Protective Factors; SDQ = Strengths &amp; Di fficulties Questionnaire; CRPBI = Child’s Report of Parental Behavior Inventory; FES = Family Environment Scale;

Complete social and political equality for the Palestinian Arab minority in Israel is only possible, even purely as an idea, if the notion of a Jewish state is understood simply as

● TIMED_WAITING: The thread is waiting by using a sleep, wait, join or park method. There is