Threads. Story so far  Our programs have consisted of single flows of control Flow of control started in the first statement of method main() and worked.

Slides:



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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Multithreading Example from Liang textbook.
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.
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.
13-Jun-15 Animation. 2 Moving pictures Animation—making objects that appear to move on the screen—is done by displaying a series of still pictures, one.
Object-Oriented Software Engineering Concurrent Programming.
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.
1 Recitation 11. Applet Applets. An applet is a Java program that is started by a browser (e.g. netscape or internet explorer) when an html file has a.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
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.
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-
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.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
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)
GUI programming Graphical user interface-based programming.
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.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
1 G53SRP: Clocks and Time in Java Chris Greenhalgh School of Computer Science.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Threading and Concurrency COM379T John Murray –
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
SurfaceView.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
© 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.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
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.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
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.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
Threads.
Multithreaded applets
Multithreading / Concurrency
Multithreading Lec 23.
Java Multithreading.
Animation 6-Nov-18.
Threads Chate Patanothai.
Multithreaded Programming in Java
Java Based Techhnology
Principles of Software Development
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.
COP 4610L: Applications in the Enterprise Spring 2005
Chapter 15 Multithreading
Threads in Java James Brucker.
Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads

Story so far  Our programs have consisted of single flows of control Flow of control started in the first statement of method main() and worked its way statement by statement to the last statement of method main() Flow of control could be passed temporarily to other methods through invocations, but the control returned to main() after their completion  Programs with single flows of control are known as sequential processes

Processes  The ability to run more than one process at the same time is an important characteristic of modern operating systems A user desktop may be running a browser, programming IDE, music player, and document preparation system  Java supports the creation of programs with concurrent flows of control – threads Threads run within a program and make use of its resources in their execution  Lightweight processes

Processes

Multithread processing

Timer and TimerTask  Among others, Java classes java.util.Timer and java.util.TimerTask support the creation and scheduling of threads  Abstract class Timer has methods for creating threads after either some specified delay or at some specific time public void schedule(TimerTask task, long m)  Runs task.run() after waiting m milliseconds. public void schedule(TimerTask task, long m, long n)  Runs task.run() after waiting m milliseconds. It then repeatedly reruns task.run() every n milliseconds. public void schedule(TimerTask task, Date y)  Runs task.run() at time t.  A thread can be created By extending TimerTask and specifying a definition for abstract method run()

Running after a delay  Class DisplayCharSequence extends TimerTask to support the creation of a thread that displays 20 copies of some desired character (e.g., “H”, “A”, or “N”)

Using DisplayCharSequence public static void main(String[] args) { DisplayCharSequence s1 = new DisplayCharSequence('H'); DisplayCharSequence s2 = new DisplayCharSequence('A'); DisplayCharSequence s3 = new DisplayCharSequence('N'); }

Defining DisplayCharSequence import java.util.*; public class DisplayCharSequence extends TimerTask { private char displayChar; Timer timer; public DisplayCharSequence(char c) { displayChar = c; timer = new Timer(); timer.schedule(this, 0); } public void run() { for (int i = 0; i < 20; ++i) { System.out.print(displayChar); } timer.cancel(); }

Implementing a run() method  A subclass implementation of TimerTask’s abstract method run() has typically two parts First part defines the application-specific action the thread is to perform Second part ends the thread  The thread is ended when the application-specific action has completed

Running repeatedly  Example Having a clock face update every second public static void main(String[] args) { SimpleClock clock = new SimpleClock(); }

public class SimpleClock extends TimerTask { final static long MILLISECONDS_PER_SECOND = 1000; private JFrame window = new JFrame("Clock"); private Timer timer = new Timer(); private String clockFace = ""; public SimpleClock() { window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setSize(200, 60); Container c = window.getContentPane(); c.setBackground(Color.white); window.setVisible(true); timer.schedule(this, 0, 1*MILLISECONDS_PER_SECOND); } public void run() { Date time = new Date(); Graphics g = window.getContentPane().getGraphics(); g.setColor(Color.WHITE); g.drawString(clockFace, 10, 20); clockFace = time.toString(); g.setColor(Color.BLUE); g.drawString(clockFace, 10, 20); }

SimpleClock scheduling

Running at a chosen time  Example Scheduling calendar pop-ups using class DisplayAlert

Using DisplayAlert public static void main(String[] args) { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 9); c.set(Calendar.MINUTE, 30); c.set(Calendar.SECOND, 0); Date studentTime = c.getTime(); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 15); c.set(Calendar.SECOND, 0); Date danceTime = c.getTime(); DisplayAlert alert1 = new DisplayAlert( "Prospective student meeting", studentTime); DisplayAlert alert2 = new DisplayAlert( "Dance recital", danceTime); }

Defining DisplayAlert import javax.swing.JOptionPane; import java.awt.*; import java.util.*; public class DisplayAlert extends TimerTask { private String message; private Timer timer; public DisplayAlert(String s, Date t) { message = s + ": " + t; timer = new Timer(); timer.schedule(this, t); } public void run() { JOptionPane.showMessageDialog(null, message); timer.cancel(); }

Sleeping  Threads can be used to pause a program for a time  Standard class java.lang.Thread has a class method sleep() for pausing a flow of control public static void sleep(long n) throws InterruptedException Pauses the current thread for n milliseconds. It then throws an InterruptedException.

Sleeping example  Code Date t1 = new Date(); System.out.println(t1); try { Thread.sleep(10000); } catch (InterruptedException e) { } Date t2 = new Date(); System.out.println(t2);  Output Fri Jan 31 19:29:45 EST 2003 Fri Jan 31 19:29:55 EST 2003