17
Threading * Advanced Java Programming Eriq Muhammad Adams J [email protected] Informatics Engineering – University

Threading Eriq Muhammad Adams J [email protected]

Embed Size (px)

Citation preview

Page 1: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Threading

*Advanced Java Programming

Eriq Muhammad Adams [email protected]

Info

rmati

cs E

ngin

eeri

ng –

Univ

ers

ity o

f B

raw

ijaya

Page 2: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Agenda

* Thread ?

* When to use threads

* Creating Threads

* Synchronization

* Avoiding Deadlock

* Demo

* Reference

Page 3: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Thread ?

*A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Page 4: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

When to use threads

*If you have any time consuming tasks or procedures.

*For example, use threads in these situations:When loading lots of files from the local file system

When doing any network communication, such as sending high scores to a server

When doing any massive calculations, such as terrain generation

Page 5: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Creating Threads

*Running threads :

MyThread myThread = new MyThread();

myThread.start();

Thread myRunnable = new Thread(runnable);

myRunnable.start();

*You’re able to create threads by extending Thread class or implement Runnable interface or using anonymous inner class.

*Using anonymous inner class :

new Thread(){

public void run(){

// do something here …

}

}.start();

Page 6: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Creating Threads (cont.)

*Implement Runnable interface :

public class MyThread implements Runnable{

Public void run(){

// do something here …

}

}

*Extending Thread class :public class MyThread extends Thread {

Public void run(){

// do something here …

}

}

Page 7: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Creating Threads (cont.)

*Use join() method, If you want your current thread to wait until a thread is finished :

myThread.join();

*Use sleep() method, If you want to make your thread sleep :

Thread.sleep(100) // sleep thread in 100 ms

Page 8: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization

*Synchronization problem occurred when you’ve got multiple threads trying to access same objects or variables.

Samples:

public class Maze {

private int playerX;

private int playerY;

public boolean isAtExit() {

return (playerX == 0 && playerY == 0);

}

public void setPosition(int x, int y) {

playerX = x;

playerY = y;

}

}

Page 9: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

*Problem :

Most of the time, this code works fine. But keep in mind that threads can be pre-empted at any time. Imagine this scenario, in which the player moves from (1,0) to (0,1):

1. Starting off, the object's variables are playerX = 1 and playerY = 0.

2. Thread A calls setPosition(0,1).

3. The line playerX = x; is executed. Now playerX = 0.

4. Thread A is pre-empted by Thread B.

5. Thread B calls isAtExit().

6. Currently, playerX = 0 and playerY = 0, so isAtExit() returns true!

In this scenario, the player is reported as solving the maze when it's not the case. To fix this, you need to make sure the setPosition() and isAtExit() methods can't execute at the same time.

Page 10: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

* Solution :

public class Maze {

private int playerX;

private int playerY;

public synchronized boolean isAtExit() {

return (playerX == 0 && playerY == 0);

}

public synchronized void setPosition(int x,

int y) {

playerX = x;

playerY = y;

}

}

Or you can do like this :

public void setPosition(int x, int y) {

synchronized(this) {

playerX = x;

playerY = y;

}

}

Page 11: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

*Object synchronization :

Object myLock = new Object();

synchronized (myLock) {

...

}

*Local synchronization :

public void myMethod() {

synchronized(this) {

// code that needs to be synchronized

}

// code that is already thread-safe

}

Page 12: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

*Using wait() and notify() : Case : Thread A waiting a message from Thread B

// Thread A

public void waitForMessage() {

while (hasMessage == false) {

Thread.sleep(100);

}

}

// Thread B

public void setMessage(String message) {

hasMessage = true;

}

It’s work but it’s chuncky

Page 13: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

Solution :// Thread A

public synchronized void waitForMessage() {

try {

wait();

} catch (InterruptedException ex) { }

}

// Thread B

public synchronized void setMessage(String message){

notify();

}

Page 14: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Synchronization (cont.)

*The wait() or wait(timeInMillis) method is used in synchronized blocks of code. When the wait() method executes, the lock is released and the thread waits to be notified.

*The notify() method is also used in a synchronized block of code. The notify() method notifies one thread waiting on the same lock. If several threads are waiting on the lock, one of them is notified randomly.

*notifyAll(), notifies all threads waiting on the lock, instead of just one.

*don't synchronize a method that uses only local variables

Page 15: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Avoiding Deadlock

*Deadlock is the result of two threads that stall because they are waiting on each other to do something.

*Consider this example:

1. Thread A acquires lock 1.

2. Thread B acquires lock 2.

3. Thread B waits for lock 1 to be released.

4. Thread A waits for lock 2 to be released.

*Please read article at :http://www.javaworld.com/javaworld/jw-10-2001/jw-1012-deadlock.html

Page 16: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Demo

*Demo available in ThreadingDemo.zip

Page 17: Threading Eriq Muhammad Adams J eriq.adams@ub.ac.id

Reference

*David Brackeen, Developing Games in Java, New Riders Publishing, 2003