Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Block 3: Threads Jin Sa

2 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

3 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

4 Two ways to define threads Extending the Thread class Implementing the Runnable interface

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

6 Key elements for extending Thread 1 class NewThread extends Thread { … //override the run method public void run() { //define how the thread runs … } … }

7 Key element for extending Thread 2 class MyApplication { … public void someMethod() { NewThread mythread=new NewThread(); … mythread.start(); } … }

8 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

9 An example: two threads printing their ids public class SeveralThreads { public static void main(String [] args) { MyThread t1,t2; //create threads t1 = new MyThread("t1"); t2 = new MyThread("t2"); //start threads t1.start(); t2.start(); }//main }//SeveralThreads

10 An example: two threads printing their ids Print thread t1 Print thread t2 Print thread t1 Print thread t2 Print thread t1 Print thread t2 Print thread t1 Print thread t2 … Run the Severalthread program in Client-Server project and thread package.

11 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

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

13 Key elements for implementing Runnable 1 class NewTask extends AnotherClass implements Runnable { … //implement the run method public void run() { //define how the thread runs … } … }

14 Key elements for implementing Runnable 2 class MyApplication { … public void someMethod() { NewTask mytask=new NewTask(); Thread mythread=new Thread(mytask); … mythread.start(); } … }

15 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

16 An example: two threads printing their ids using implementing Runnable public class SeveralThreads { public static void main(String[] args) { //create instances of MyTask MyTask 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

17 Multithreading for user interface in GUI applications

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

19 Flash rectangle 1 class FlashRec extends JPanel implements Runnable{ private boolean keepgoing=true; public void pleaseStop() { keepgoing=false; } public void pleaseStart(){ keepgoing=true; } To continue…

20 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

21 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; …

22 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

23 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

24 Thread synchronisation

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

26 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

27 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

28 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

29 Problem with accessing shared resources– an example 4 Run FamilyAccount in the threads package in ClientServer project. The result should be: The balance is : £10 The balance is : £20 The balance is : £30 … The balance is : £200 But a shared resource may be corrupted if it is accessed simultaneously by multiple threads

30 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!

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

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

33 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

34 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

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

36 Cooperation among threads Synchronization avoid race condition through mutual exclusion of critical region. Java provide a concept called Condition to facility thread cooperation.

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

38 Deposit and withdraw money Spender 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.

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

40 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 }

41 Account example-revisited 2 class 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(); }

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

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


Download ppt "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."

Similar presentations


Ads by Google