block 3: threads jin sa. outline of block 3 why multi-threads defining and creating threads an...

43
Block 3: Threads Jin Sa

Post on 21-Dec-2015

246 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Block 3: Threads

Jin Sa

Page 2: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Outline of block 3

• Why multi-threads• Defining and creating threads• An example with two threads• Life cycle of a thread• An example with user interface• Problem with threads• Synchronisation among threads• Thread collaboration

Page 3: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Why multithreading?

• Most of the programs we have seen so far can only do one thing at a time. In the real world many actions are happening concurrently.

• Typical applications: – User interfacing For some applications, e.g.

graphics, we may need more than one thread. One deals with the drawing, the other deals with user interface

– Many instances Many instances of similar behaviour or many different tasks

Page 4: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Two ways to define threads

• Extending the Thread class

• Implementing the Runnable interface

Page 5: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Creating threads by extending the Thread class

• Define a class, e.g. NewThread, extending the Thread class

• Override the run() method to tell the system how the thread will be executed when it runs.

• Create an instance of NewThread, • Invoke the start() method to tell the system to

start the thread and to execute the run() method.

Page 6: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Key elements for extending Thread 1

class NewThread extends Thread {

//override the run method

public void run() {

//define how the thread runs

}

}

Page 7: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Key element for extending Thread 2

class MyApplication {

public void someMethod() {

NewThread mythread=new NewThread();

mythread.start();

}

}

Page 8: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

An example: a thread printing its id repeatedly

class MyThread extends Thread {

private String threadID;

MyThread(String s) { threadID=s; }

public void run() {

for (int i=0;i<200;i++){

System.out.println("Print thread "

+ threadID);

}//for

}//run

} //MyThread

Page 9: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

An example: two threads printing their ids

public class SeveralThreads {

public static void main(String [] args) {MyThread t1,t2;

//create threadst1 = new MyThread("t1");t2 = new MyThread("t2");

//start threads t1.start();

t2.start();}//main

}//SeveralThreads

Page 10: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

An example: two threads printing their ids

Print thread t1Print thread t2Print thread t2Print thread t1Print thread t1Print thread t2Print thread t1Print thread t2Print thread t1Print thread t2…

Run the Severalthread program in Client-Server project and thread package.

Page 11: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Life cycle of a thread

• A thread can be in one of these states once it is created: ready, running, blocked, finish

• A ready thread is runnable, but not running, it needs allocation of CPU time.

• Common ways for a running thread to become blocked include: waiting for I/O, sleep

• A common way for a thread to finish is when it completes its execution of the run() method

Page 12: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Creating threads by implementing the Runnable interface

• Use Runnable if need to extend another class• Define a class, e.g. NewTask, implementing the Runnable interface

• implement the run() method to tell the system how the task will be executed when it runs.

• Create an instance of NewTask, e.g. t1• The task needs to be executed in a thread. Create

an instance of Thread with t1 as the parameter• Invoke the start() method of the thread to tell

the system to start the thread.

Page 13: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Key elements for implementing Runnable 1

class NewTask extends AnotherClass implements Runnable {…//implement the run methodpublic void run() {

//define how the thread runs…

}…

}

Page 14: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Key elements for implementing Runnable 2

class MyApplication {…public void someMethod() {

NewTask mytask=new NewTask();Thread mythread=new Thread(mytask);

…mythread.start();

}…

}

Page 15: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

An example: thread printing its id using implementing Runnable

class MyTask implements Runnable { private String threadID; MyTask(String s) { threadID=s; } public void run() { for (int i=0;i<200;i++){ System.out.println("Print thread " + threadID); }//for }//run } //MyTask

Page 16: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

An example: two threads printing their ids using implementing

Runnable public class SeveralThreads { public static void main(String[] args) {

//create instances of MyTaskMyTask t1 = new MyTask("t1");MyTask t2 = new MyTask("t2");

// create Thread instances Thread tt1=new Thread(t1); Thread tt2=new Thread(t2);

//start threads tt1.start();

tt2.start();}//main

}//SeveralThreads

Page 17: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Multithreading for user interface in GUI applications

Page 18: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Example: Flashing label

• Run the StartStop program. (in ClientServer project, threads package)

• Press start, program displays a flashing rectangle until user presses the stop button.

• One thread is tied to display the flashing rectangle.

• In order to be able to accept user’s input, need more than one thread.

Page 19: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Flash rectangle 1class FlashRec extends JPanel implements

Runnable{

private boolean keepgoing=true;

public void pleaseStop() {

keepgoing=false;

}

public void pleaseStart(){

keepgoing=true;

}

To continue…

Page 20: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Flash rectangle 2

public void run() { while (keepgoing) { try { setBackground(Color.red); Thread.sleep(400); setBackground(Color.white); Thread.sleep(400); } catch (Exception e) {} }//while }//run}//FlashRec

Page 21: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

User interface thread 1

public class StartStop extends JFrame

implements ActionListener {

private JButton start=

new JButton("start");

private JButton stop=new JButton("stop");

private FlashRec fr;

private Thread recThread;

Page 22: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

User interface thread 2

StartStop() { setSize(400,200); fr=new FlashRec(); Container c = getContentPane(); c.add(start, "North"); start.addActionListener(this); c.add(stop,"South"); stop.addActionListener(this); c.add(fr, "Center");// }//StartStop

Page 23: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

User interface thread 3

public void actionPerformed(ActionEvent e) { if (e.getSource() == start ) { fr.pleaseStart(); recThread=new Thread(fr); recThread.start();}//if if (e.getSource() ==stop) { fr.pleaseStop();} }//actionPerformed

Page 24: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Thread synchronisation

Page 25: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem with accessing shared resources– an example

• The Account class is a bank account, contains methods such as deposite and withdraw.

• Cardholder is a thread allows the card holder to deposite £10 repeatedly for 10 times.

• FamilyAccount has a main methods that creates one instance of an Account, two instances of Cardholders, both putting money into the same account.

Page 26: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem with accessing shared resources– an example 1

class Account { int balance=0;

public void deposit(int amount) { balance = balance + amount; } public void printDetails() { System.out.println("The balance is : "+ balance);

}}//Account

Page 27: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem with accessing shared resources– an example 2

class CardHolder extends Thread{ Account acc; CardHolder(Account a) { acc=a; }

public void run() { for (int i=0;i<10;i++) { acc.deposit(10); acc.printDetails(); } }//run

}//CardHolder

Page 28: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem with accessing shared resources– an example 3

class FamilyAccount { public static void main(String [] args) { Account ourAccount=new Account(); CardHolder husband = new CardHolder(ourAccount); CardHolder wife = new CardHolder(ourAccount); ourAccount.printDetails(); husband.start(); wife.start(); }}//FamilyAccount

Page 29: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem with accessing shared resources– an example 4

• Run FamilyAccount in the threads package in ClientServer project.

• The result should be:The balance is : £10The balance is : £20The balance is : £30…The balance is : £200• But a shared resource may be corrupted if it is

accessed simultaneously by multiple threads

Page 30: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Problem• For example, the current balance in ourAccount is £50,• The husband thread: tries to deposit £10; loading the current

value, i.e. 50, to the temporary storage place before doing the arithmetic. The thread is suspended; switches to the wife thread.

• The wife thread: tries to deposit £10; loading the current balance, which is still £50. The thread is then suspended; resumes the husband thread,

• Back with the husband thread: add £10 to the value, i.e. £50, in the temporary storage; £60 is stored in the attribute balance; suspend the husband thread

• Back with the wife thread: the wife thread adds £10 to the current value in the temporary storage that is 50. The result 60 is now stored in the balance attribute.

• In fact it should be 70, not 60!

Page 31: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Race condition

• The problem is that the two threads (husband and wife) are accessing the same resource (account) in a way that causes a conflict.

• This is a common problem, known as a race condition, in multithreaded programs.

• A class is said to be thread-safe if an object of the class does not cause a race condition in the presence of multiple threads.

• The Account class is not thread-safe at the moment.

Page 32: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Synchronized method

• There is a need to protect the shared data.• Use synchronized methods so that there can be

only one thread executing this method at a time.• Java guarantees once a thread has gained access to

a synchronized method, it will finish the method before any other thread gains access to that or any other synchronized method in that object.

• A synchronised method (implicitly) acquires a lock on the instance.

Page 33: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Deposit as a Synchronized method

class Account { int balance=0;

public synchronized void deposit(int amount) { balance = balance + amount; } public void printDetails() { System.out.println("The balance is : "+

balance); }}//Account

• Run the program

Page 34: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Synchronization using locks

• JDK 1.5 has a new (explicit) locking facility to give programmers more control to coordinate threads.

• Interface Lock has: lock(), unlock() and newCondition()

• Class ReentrantLock implements Lock

Page 35: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Using lock for the deposit method

public void deposit(int amount) { //public synchronized void deposit(int amount) { mylock.lock(); // balance = balance +amount; int tmp = balance; busyDoingSomething(); //trying to intrduce some delay to show the

interleaving balance = tmp + amount; mylock.unlock(); }• Achieve the same event as synchronized method (block), but more

flexible.

Page 36: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Cooperation among threads

• Synchronization avoid race condition through mutual exclusion of critical region.

• Java provide a concept called Condition to facility thread cooperation.

Page 37: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Example of thread cooperation

• Add a new method withdraw from an Account object.

• One thread deposit money, one thread withdraw money.

• In order to withdraw, needs to make sure the balance is more than amount to be withdraw. If not, the thread waits for the other thread to deposit more money.

Page 38: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Deposit and withdraw moneySpender

Loop 10 times:

enough money?

No, Await until being notified

Take £10

Earner

Loop 10 times:

Put £10

Notify anyone who is waiting

Run FamilyAccount_2 to show the cooperation between earner and spender.

Page 39: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Condition

• A Condition object is created invoking a lock objetc’s newCondition method, e.g.

Lock mylock = new ReentrantLock;

Condition enoughMoney=mylock.newCondition();

• withDraw method checks if there is enough balance; if not, invoke the await() method on the condition enoughtMoney; and waits until it is notified to try again.

• deposit method invokes the singalAll() on the condition enoughMoney after it adds some money to the balance.

Page 40: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Account example-revisited 1

import java.util.concurrent.locks.*;class Account_2 { int balance=0; Lock mylock=new ReentrantLock(); Condition enoughMoney= mylock.newCondition(); … see the next two slides }

Page 41: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Account example-revisited 2class Account_2 { … public void withdraw(int amount){ mylock.lock(); while (balance<amount) { try { System.out.println("not enough, wait ..."); enoughMoney.await(); } catch (Exception e) {} } balance=balance-amount; System.out.println("Current balance is "+balance); mylock.unlock(); }}

Page 42: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Account example-revisited 3class Account_2 { … public void deposit(int amount) { mylock.lock(); balance = balance +amount; System.out.println("Current balance is "+balance); enoughMoney.signalAll(); mylock.unlock(); }}

Page 43: Block 3: Threads Jin Sa. Outline of block 3 Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example

Java Built-in monitor

• Locks and Conditions are new in Java 5. • Before the introduction of the Locks and

Conditions, thread communications were achieved using wait(), notify() and notifyAll() on objects.

• Using the new await(), signal() and signalAll() on Conditions are much more flexible and powerful.