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.

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

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
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.
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.
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-
Java Threads CS Introduction to Operating Systems.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
1 Java Threads Instructor: Mainak Chaudhuri
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)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
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.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
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
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
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.
Java 3: Odds & Ends Advanced Programming Techniques.
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. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
© Andy Wellings, 2004 Thread Priorities I  Although priorities can be given to Java threads, they are only used as a guide to the underlying scheduler.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Multithreading 2 Lec 24.
Java Based Techhnology
Principles of Software Development
Multithreading.
Multithreaded Programming
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads in Java James Brucker.
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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. b When a Java Virtual Machine starts up, there is usually a single thread (which typically calls the method named main of some designated class).

Understanding Threads b You must be able to answer the following questions What code does a thread execute?What code does a thread execute? What states can a thread be in?What states can a thread be in? How does a thread change its state?How does a thread change its state? How does synchronization work?How does synchronization work?

Thread Objects b As is everything else, threads in Java are represented as objects. b The code that a thread executes is contained in its run() method. There is nothing special about run, anyone can call it.There is nothing special about run, anyone can call it. b To make a thread eligible for running you call its start() method

Example public class CounterThread extends Thread { public void run() { for ( int i=0; i<10; i++) System.out.println(“Count: “ + i); } public static void main(String args[]) { CounterThread ct = new CounterThread(); ct.start(); }

Interface Runnable b Classes that implement Runnable can also be run as separate threads b Runnable classes have a run() method b In this case you create a thread specifying the Runnable object as the constructor argument

Example public class DownCounter implements Runnable { public void run() { for (int i=10; i>0; i--) System.out.println(“Down: “+ i); } public static void main(String args[]) { DownCounter ct = new DownCounter(); Thread t = new Thread(ct); t.start(); }

Many public class Many extends Thread { private int retry; private String info; public Many (int retry, String info) { this.retry = retry; this.info = info; } public void run () { for (int n = 0; n < retry; ++ n) work(); quit(); } protected void work () { System.out.print(info); } protected void quit () { System.out.print('\n'); } public static void main (String args []) { if (args != null) for (int n = 0; n < args.length; ++n) new Many(args.length, args[n]).start(); }}

When Execution Ends b The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been calledThe exit method of class Runtime has been called All threads that are not daemon threads have died, either by returning from the call to the run() or by throwing an exception that propagates beyond run().All threads that are not daemon threads have died, either by returning from the call to the run() or by throwing an exception that propagates beyond run(). b You cannot restart a dead thread, but you can access its state and behavior.

Thread Scheduling b Threads are scheduled like processes b Thread states RunningRunning Waiting, Sleeping, Suspended, BlockedWaiting, Sleeping, Suspended, Blocked ReadyReady DeadDead b When you invoke start() the Thread is marked ready and placed in the thread queue

Thread States Running Ready Waiting The start() method places a thread in the ready state The scheduler selects a thread and places it in the running state A thread that is waiting for I/O, was suspended, is sleeping, blocked, or otherwise is unable to do any more work is placed in the waiting state

isAlive() b The method isAlive() determines if a thread is considered to be alive A thread is alive if it has been started and has not yet died.A thread is alive if it has been started and has not yet died. b This method can be used to determine if a thread has actually been started and has not yet terminated

isAlive() public class WorkerThread extends Thread { private int result = 0; public void run() { // Perform a complicated time consuming calculation // and store the answer in the variable result } public static void main(String args[]) { WorkerThread t = new WorkerThread(); t.start(); while ( t.isAlive() ); // What is wrong with this? System.out.println( result ); }

sleep() b Puts the currently executing thread to sleep for the specified number of milliseconds sleep(int milliseconds)sleep(int milliseconds) sleep(int millisecs, int nanosecs)sleep(int millisecs, int nanosecs) b Sleep can throw an InterruptedException e.g. on another thread interrupt()e.g. on another thread interrupt() b The sleep method is static and can be accessed through the Thread class name

sleep() public class WorkerThread extends Thread { private int result = 0; public void run() { // Perform a complicated time consuming calculation // and store the answer in the variable result } public static void main(String args[]) { WorkerThread t = new WorkerThread(); t.start(); while ( t.isAlive() ) try { sleep( 100 ); } catch ( InterruptedException ex ) {} System.out.println( result ); }

Timer import java.util.Date; class Timer implements Runnable { public void run() { while ( true ) { System.out.println( new Date() ); try { Thread.sleep(1000); } catch ( InterruptedException e ) {} } public static void main( String args[] ) { Thread t = new Thread( new Timer() ); t.start(); System.out.println( "Main done" ); }

Problems b In thread A: personsDictionary.delete(“niceName”)personsDictionary.delete(“niceName”) b In thread B: personsDictionary.add(person)personsDictionary.add(person) b The linked list can be corrupted. b To update the state of the object safely from different threads the methods should be synchronized: public synchronized boolean personsDictionary.add(…) {…}public synchronized boolean personsDictionary.add(…) {…} public synchronized boolean personsDictionary.delete(…){…}public synchronized boolean personsDictionary.delete(…){…}

b In the project: if only the receiving thread accesses the data we have no problemif only the receiving thread accesses the data we have no problem b But: Unlike AWT, Swing is not thread-safeUnlike AWT, Swing is not thread-safe Problems

yield() b A call to the yield() method causes the currently executing thread to go to the ready state (this is done by the thread itself)

yield() public class WorkerThread extends Thread { private int result = 0; public void run() { // Perform a complicated time consuming calculation // and store the answer in the variable result } public static void main(String args[]) { WorkerThread t = new WorkerThread(); t.start(); while ( t.isAlive() ) yield() System.out.println( result ); }

Joining Threads b Calling isAlive() to determine when a thread has terminated is probably not the best way to accomplish this b What would be better is to have a method that once invoked would wait until a specified thread has terminated b join() does exactly that join()join() join(long timeout)join(long timeout) join(long timeout, int nanos)join(long timeout, int nanos) b Like sleep(), join() is static and can throw an InterruptedException

join() public class WorkerThread extends Thread { private int result = 0; public void run() { // Perform a complicated time consuming calculation // and store the answer in the variable result } public static void main(String args[]) { WorkerThread t = new WorkerThread(); t.start(); try { t.join(); } catch ( InterruptedException ex ) {} System.out.println( result ); }

Thread Priorities b Threads can have priorities from 1 to 10 (10 is the highest) b The default priority is 5 The constants Thread.MAX_PRIORITY, Thread.MIN_PRIORITY, and Thread.NORM_PRORITY give the actual valuesThe constants Thread.MAX_PRIORITY, Thread.MIN_PRIORITY, and Thread.NORM_PRORITY give the actual values b Priorities can be changed via setPriority() (there is also a getPriority())