Download presentation
Presentation is loading. Please wait.
1
Multithreading 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
2
Why multithreading? So far the programs 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
3
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.
4
Key elements for extending Thread 1 class NewThread extends Thread { … //override the run method public void run() { //define how the thread runs … } … }
5
Key element for extending thread 2 class MyApplication { … public void someMethod() { NewThread mythread=new NewThread(); … mythread.start(); } … }
6
An example of two threads 1 class MyThread extends Thread { private String threadID; MyThread (String s) { threadID=s; } public void run() { for (int i=0;i<5;i++){ try {System.out.println("Print thread " + threadID); Thread.sleep(20);// to show interleave } catch (InterruptedException e) {} }//for }//run } //MyThread
7
An example of two threads 2 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
8
An example of two threads 3 Print thread t1 Print thread t2 Print thread t1 Print thread t2 Print thread t1 Print thread t2 Print thread t1 Print thread t2
9
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
10
Creating threads by implementing the runnable interface Define a class, e.g. NewThread, implementing the runnable interface implement 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.
11
Key elements for implementing Runnable class NewThread extends AnotherClass implements Runnable { … //implement the run method public void run() { //define how the thread runs … } … }
12
An example with user interface 1 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class StartStop extends JFrame implements ActionListener { private JButton start=new JButton("start"); private JButton stop=new JButton("stop"); private FlashRec fr; StartStop () { Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(start); start.addActionListener(this); c.add(stop); stop.addActionListener(this); }//StartStop
13
An example with user interface 2 public void actionPerformed(ActionEvent e) { if (e.getSource() == start ) { Graphics g = getGraphics(); fr = new FlashRec(g); fr.start();// start the thread fr }//if if (e.getSource() ==stop) { fr.pleaseStop();} }//actionPerformed public static void main(String [] args) { StartStop ss = new StartStop (); ss.setVisible(true); }//main }//StartStop
14
An example with user interface 3 class FlashRec extends Thread{ private Graphics g; private boolean keepgoing=true; FlashRec(Graphics g) { this.g=g; } public void pleaseStop() {keepgoing=false;} public void run() { while (keepgoing) { g.setColor(Color.white); g.drawRect(100,100,200,50); g.setColor(Color.red); g.fillRect(100,100,200,50); }//while }//run }//FlashRec
15
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.
16
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
17
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
18
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
19
Problem with accessing shared resources– an example 4 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
20
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!
21
Synchornized 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.
22
Deposit as a Synchronzed method class Account { int balance=0; public synchrozed void deposit(int amount) { balance = balance + amount; } public void printDetails() { System.out.println("The balance is : "+ balance); } }//Account
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.