Multithreading Why multi-threads Defining and creating threads An example with two threads Life...

22
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
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    228
  • download

    0

Transcript of Multithreading Why multi-threads Defining and creating threads An example with two threads Life...

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

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

Page 2: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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

Page 3: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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.

Page 4: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

Key elements for extending Thread 1

class NewThread extends Thread {

//override the run method

public void run() {

//define how the thread runs

}

}

Page 5: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

Key element for extending thread 2

class MyApplication {

public void someMethod() {

NewThread mythread=new NewThread();

mythread.start();

}

}

Page 6: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

An example of two threads 1class 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

Page 7: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

An example of two threads 2

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 8: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

An example of two threads 3

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

Page 9: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 10: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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.

Page 11: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

Key elements for implementing Runnable

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

//define how the thread runs…

}…

}

Page 12: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

An example with user interface 1import 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

Page 13: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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

Page 14: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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

Page 15: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 16: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 17: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 18: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 19: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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

Page 20: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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 21: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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.

Page 22: Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.

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