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

Slides:



Advertisements
Similar presentations
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Multithreading A thread is the flow of execution, from beginning to end, of a task in a program. With Java, you can launch multiple threads from a program.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
1 Threads (Part II) Threads and Concurrency (Part II) Overview  Review of Previous Lecture.  Controlling Threads and Thread State.  Example 1: Creating.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Threads CS Introduction to Operating Systems.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples.
Multithreading.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
1 Java Threads Instructor: Mainak Chaudhuri
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Computer Engineering Rabie A. Ramadan Lecture 8. Agenda 2 Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
Concurrent Programming and Threads Threads Blocking a User Interface.
C20: Threads see also: ThreadedBallWorld, DropTest, Tetris source examples Not covered: advanced stuff like notify/notifyAll.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Java Thread Programming
Multithreaded applets
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Object-Orientated Analysis, Design and Programming
Advanced Programming in Java
Java Based Techhnology
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads in Java James Brucker.
Threads and Multithreading
Representation and Management of Data on the Internet
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

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

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.

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

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

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

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

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

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

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.

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

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

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

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

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.

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

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

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

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

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!

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.

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