Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

CS4273: Distributed System Technologies and Programming I Lecture 4: Java Threads and Multithread Programming.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
2. Java and Concurrency Prof. O. Nierstrasz Selected material © Magee and Kramer.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Object-Oriented Software Engineering Concurrent Programming.
CP — Concurrent Programming 2. Java and Concurrency Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CSE S. Tanimoto Java Threads 1 Java Threads (Outline) Motivation The class Thread Example program: ThreadRace The Runnable interface Example: Clock.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
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.
ThreadThread Thread Basics Thread Synchronization Animations.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Clocks & Asynchronous Events. Overview Clocks  API  Implementation Asynchronous Events  API  Single Threaded Model  Multi-Threaded Model  Code Walkthrough.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Multithreading.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
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.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads CSCE 190 – Java Instructor: Joel Gompert Wed, Aug 3, 2004.
1 Web Based Programming Section 8 James King 12 August 2003.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Chapter 6 (6.7 & 6.9 only) - Threads & Mutex Threads –A Thread is a basic unit of CPU utilization consisting of a program counter, register set and stack.
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.
Multithreading in JAVA
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Threading and Concurrency COM379T John Murray –
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multi-Threading in Java
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Distributed and Parallel Processing George Wells.
Chapter 13: Multithreading
Lecture 9 Object Oriented Programming Using Java
THREADS.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Based Techhnology
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
برنامه‌نویسی چندنخی Multi-Thread Programming
Chapter 15 Multithreading
Threads in Java James Brucker.
Multithreading in java.
Representation and Management of Data on the Internet
Gentle Introduction to Threads
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science

Computer Science, University of Karlstad2 Thread Definition: l A thread is a single sequential flow of control within a program.

Computer Science, University of Karlstad3 Introduction A thread l is an instantiation of a code running in a separate time space l is a convenient means for synchronization of asynchronous tasks l is running in the parent process’ address space

Computer Science, University of Karlstad4 Introduction A thread is not l a process, it does not have an address space l an OS task, it is part of its parent task

Computer Science, University of Karlstad5 Multiple Threads can run in a Single Program

Computer Science, University of Karlstad6 The Basic Idea, Example Create some need get information continue Produce something deliver continue transfer wait ProducerConsumer

Computer Science, University of Karlstad7 Threads run public class SimpleThread extends Thread { public SimpleThread(String name) { super(name); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } Called when the thread is start() -ed

Computer Science, University of Karlstad8 Threads run in Parallel public class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); }

Computer Science, University of Karlstad9 A Possible Result 0 Jamaica 0 Fiji 1 Fiji 1 Jamaica 2 Jamaica 2 Fiji 3 Fiji 3 Jamaica 4 Jamaica 4 Fiji 5 Jamaica 5 Fiji 6 Fiji 6 Jamaica 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica

Computer Science, University of Karlstad10 The Life Cycle of a Thread

Computer Science, University of Karlstad11 Threads

Computer Science, University of Karlstad12 Implementing the Runnable Interface public class Clock extends Applet implements Runnable { private Thread clockThread = null; public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } Applet.start() Thread.start()

Computer Science, University of Karlstad13 Runnables

Computer Science, University of Karlstad14 Implementing the Runnable Interface public void run() { Thread myThread = Thread.currentThread() while (myThread == clockThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){} // the VM doesn't want us to sleep // anymore, so get back to work } // My creator has nulled out clockThread // to signal that I should stop working } // run

Computer Science, University of Karlstad15 Thread synchronization: example Public class ThreadApplet extends SequentialApplet { public void start() { new Thread(hello).start(); new Thread(goodbye).start(); }

Computer Science, University of Karlstad16 hello and goodbye are two Runnable objects display hello or goodbye in a common text area txt l use the Java awt function appendText for the display l code page 9 –run() {txt.appendText(msg);}

Computer Science, University of Karlstad17 hello and goodbye

Computer Science, University of Karlstad18 Interaction diagrams: Description l Like the GoF patterns, interaction diagrams describe the flow of control l Unlike the GoF patterns the diagrams show discrete steps per thread –no synchronization is implied between the threads

Computer Science, University of Karlstad19 Interaction diagram: Example goodbye applethello start start/run appendText return

Computer Science, University of Karlstad20 Java synchronization primitives l to avoid interference when more than one concurrent thread can execute a function on a shared object the keyword synchronized locks out other synchronized threads from that object

Computer Science, University of Karlstad21 Synchronized wrapper l assume appendText was not already synchronized –could produce l HeGoodlbye lo l GHoeoldlbo ye –or other funny output instead of l Hello Goodbye (or the other way round)

Computer Science, University of Karlstad22 Synchronized wrapper class Appender { // page 17 private TextArea textArea; Appender(TextArea t) { textArea = t; } synchronized void append(String s) { textArea.appendText(s); }

Computer Science, University of Karlstad23 What is synchronized? l Always an object –the object executing a synchronized method –an explicitly mentioned object Object syncher = new Object; void f1() {… synchronized(syncher) {…} … } void f2() {… synchronized(syncher) {…} … } only one block is executed at a time –a synchroinzed method synchronized on the current object ( l synchronized(this) {…}

Computer Science, University of Karlstad24 Giving up a synch wait suspends the current thread and releases synchronization l another waiting thread synchronized on that object can proceed the other thread can resume the waiting thread –normally using notifyAll(); l one of the waiting threads starts when the lock is freed