Advanced Java Class Threads.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Software Engineering Oct-01 #11: All About Threads Phil Gross.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
A few words regarding the “SQL injection” threat
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Internet Software Development More stuff on Threads Paul Krause.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
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.
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.
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Java 3: Odds & Ends Advanced Programming Techniques.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multi-Threading in Java
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
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.
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
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.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
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.
Threads and Multithreading
Multithreading.
Multithreading.
Multithreaded Programming
Java Concurrency 17-Jan-19.
Computer Science 2 06A-Java Multithreading
Java Concurrency.
Multithreading in java.
Java Concurrency.
Threads and Multithreading
Threads.
Concurrent programming
Java Concurrency 29-May-19.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Advanced Java Class Threads

Why Use Multiple Threads User input thread & data-processing thread user-input has high priority but users are slow (compared to CPUs) so keep processing while waiting One thread per user Model independent objects in simulations Like traffic in Frogger !!!

Thread API & Features Thread class Runnable interface Timer & TimerTask classes ThreadLocal class synchronized keyword wait(), notify(), notifyAll() (methods inherited from Object class) ThreadGroup class

Multi-threaded Processing JVM schedules processor time for each thread and dictates when they get control You can not know or control exactly how this happens, and it will be different on different systems Different threads might “share” objects, so you don’t know which thread will access it first. You can schedule priorities for threads.

Making Your Own Threads You have 2 options: extend Thread Fine if you’re not trying to extend anything else You get your thread directly by instantiating your class implement Runnable interface More flexible, therefore usually preferred. Your class can be a part of a class hierarchy unrelated to threads. You get your thread by passing an instantiation of your Runnable class to the thread constructor Either way, you deal with a Thread object.

Extending the Thread class you must override run()with the code that this thread should execute when running Instantiate your class Don’t call run()!!! Call start() to begin execution.

Implementing Runnable Interface Do this when you want to extend some other class. You must implement the run() method Create a new instance of the Runnable Pass it to the thread constructor. new Thread( myRunnable ) Call start (and other methods) on the thread, as before.

Thread Methods Static currentThread() Accessors getPriority() & setPriority(int) isDaemon() & setDaemon(boolean) isAlive() Thread Control start() [which calls run()] sleep() yield() join() Once a Thread has finished execution, is it dead and may not be restarted. hi

Thread State Diagram improved version of figure 5-2, page 333

Deprecated Thread methods You should not use stop(), suspend(), and resume() to control threads ! Reason: inherently unsafe: may leave data in an inconstant state. Deprecated since 1.2, which was when they figured this out. Instead, use flags (see next slide) ...

Alternatives to Deprecated Thread Methods Give your Runnable class volatile boolean fields, possibly named ‘suspendFlag’ & ‘stopFlag’ Provide setters for them, possibly named ‘setSuspend(boolean)’ and ‘stopThread()’ Have your code check them frequently when stopFlag is true, end the run method, leaving the data in a consistent state when suspendFlag is true, have the Thread sleep a little bit, and then check the flag again.

Special Kinds of Threads Daemon Threads continuous loop running in background listens for and handles requests when your program has only daemon threads left running, they are terminated and the application closes, because daemon threads normally never terminate on their own. TimerTask Threads you can schedule tasks to be done later run in background threads controlled by Timer objects use only for short tasks

Using TimerTasks Basics: Additional TimerTask methods: extend TimerTask implement run() method instantiate your TimerTask subclass instantiate Timer schedule your TimerTask with the Timer Additional TimerTask methods: long scheduledExecutionTime() void cancel()

How to schedule a TimerTask in a Timer Schedule an event to happen at a certain time, or after a certian delay: myTimer.schedule( myTask, time ) myTimer.schedule( myTask, delay ) Optionally, add a period parameter for recurring events. The period specifies the time between repeat occurances myTimer.schedule( myTask, time, period ) myTimer.schedule( myTask, delay, period) For tasks where the absolute timing of recurring events is important, like a clock striking on the hour, use these methods instead. If event is a little late, the others will ‘catch up’. myTimer.scheduleAtFixedRate(myTask, time, period ) myTimer.scheduleAtFixedRate(myTask, delay, period)

Good Multi-threading Techniques If a variable should only be accessed by one thread, make it “Thread-safe”. If variables could be accessed by more than one thread, do one of the following: synchronize the code that calls them declare them volatile Think about how your threads could interfere with each other – try to avoid deadlock!

Thread-Safety Local variables are automatically thread-safe Instance variables of an object whose methods are run by multiple threads are not safe declare methods that access it synchronized or declare the variable volatile Class (a.k.a. static) variables are not thread-safe or make them of type ThreadLocal or InheritableThreadLocal

Using ThreadLocal and InheritableThreadLocal Good for when you want the field to be shared by multiple instances of the same class that are running in the same Thread, but not shared with instances of the class that are running on other Threads InheritableThreadLocal allows child Threads to share the variable with parent Threads. Methods: Object get() Object initialValue() void set( Object value)

Synchronization of methods Why: to keep your variables in a consistent state How: declare the methods that access them to be synchronized What: JVM requires that no thread can access a method that another thread is currently in: provides a “lock” on the object (if instance method) or class (if static method)

Synchronization of code blocks syntax: synchronized ( object_to_be_locked ) [fill in statement or code block] when to use: If a method is long, and many threads request it, synchronizing the smallest block of code that keeps the variables consistent will reduce the chance of deadlock.

Synchronization and Inner Classes An inner class object has access to fields of the outer class object. These outer class instance variables may need to be protected in multithreaded programs. simply synchronizing the methods may not protect the outer class fields, the inner methods will be locked with the inner class instance and the outer methods will be locked with the outer class instance Therefore, an outer class method and an inner class method might run in parallel in different threads, causing inconsistent field values. Solution: instead of synchronizing the inner class method, synchronize the code with the enclosing object as a lock (see previous slide for syntax)

Communicating with wait() and notify() methods inherited from Object that affect Threads: wait() wait(long timeout) wait(long timeout, int timeoutAddNanos) notify() notifyAll() Any object can call these, but only when the current Thread has a lock on the object. These methods are final -- they may not be overridden.

The wait methods [Inherited from Object] Tells the current thread to release it’s lock, chill, and let another Thread (chosen by the JVM) execute wait() – waits until notified by another thread wait( long timeout ) – waits for the specified number of milliseconds wait( long timeout, int timeoutAddNanos) – waits for the specified number of milliseconds + the specified number of nanoseconds

The notify methods [Inherited from Object] notify() - the JVM chooses one thread that has been waiting, and puts it into a runnable state. As soon as it can aquire the needed lock, it starts. notifyAll() – the JVM places all waiting threads into a runnable state, and then chooses one to get control and execute. The others are poised, ready to go as soon as they can get the necessary lock.

When to use wait and notify When a Thread needs to wait until a particular condition is satisfied before continuing. Alternative to sleep() Typical usage: while (condition) { wait(); } (Check the condition again when notified in case the notification was unrelated to your condition) Use notify() when efficiency is a special concern, and all waiting threads are waiting for the same Object lock, so that any Thread the JVM chooses would be appropriate. Use notifyAll() when Threads are waiting for different Object locks. Each thread will check it’s condition, and at least one Thread should become able to continue.

Thread Grouping Why: What: you can protect one group of threads from another you can perform operations [setPriority or interrupt) on all the threads in the group at once, instead of having to iterate through What: stores a collection of Threads that have a special security relationship to each other each ThreadGroup can also have child ThreadGroups, allowing for a ThreadGroup heirarchy

ThreadGroup class methods include: int activeCount() & int activeGroupCount() int enumerate(Thread[] list, boolean recurse] ) int enumerate(ThreadGroup[] list, boolean recurse] ) int getMaxPriority() & void setMaxPriority() String getName() & ThreadGroup getParent() [set by constructor] boolean isDaemon() & void setDaemon(boolean daemon) list() [prints debugging info to System.out] interrupt()

ThreadGroups, continued Threads can only modify each other (like setting their priorities) if they are in the same ThreadGroup By default, Threads go in the same ThreadGroup as the Thread that created it. To override this default behavior, pass a ThreadGroup to the Thread constructor. A Thread’s ThreadGroup cannot be changed.

Threads & Anonymous Inner Classes: FileWatcher Exercise Complete the following class definition. Use an anonymous inner class that extends Thread. It should print a line to System.out when the file is created, or immediately if it already exists. You can not add code anywhere other than inside the watchFile method definition. import java.io.File; public class FileWatcher { public void watchFile( final String fileName ) { //fill this in, please. }

FileWatcher Solution t = new Thread() { File f = new File(fileName); import java.io.File; public class FileWatcher { public void watchFile(final String fileName) { Thread t; t = new Thread() { File f = new File(fileName); public void run () { while (!f.exists()) { try { sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(fileName+" exists!"); }; t.start();

Threads & Anonymous Inner Classes: Timer Exercise import java.util.*; public class Alarm { private static Timer timer = new Timer(); public static void stopAlarms() { timer.cancel(); } public static void setRecurringAlarm(final String msg, long interval) { /* Fill this in, please. After the interval specified by the parameter, the msg should be printed to System.out. After another interval, print the alarm msg again. Repeat... */ public static void main(String[] args) { Set up two alarms, one that prints “one second has passed” every second, and one that prints “five seconds have passed” every five seconds. Let them both go for twenty seconds, then stop them. After they have stopped, print “alarms stopped!”, and then the program should exit normally.

Timer Exercise Solution import java.util.*; public class Alarm { private static Timer timer = new Timer(); public static void stopAlarms() { timer.cancel(); } public static void setRecurringAlarm(final String msg, long interval) { TimerTask task = new TimerTask() { public void run() { System.out.println(msg); }; timer.scheduleAtFixedRate(task, interval, interval); public static void main(String[] args) { long oneSecond = 1000, fiveSeconds = 5000, twentySeconds = 20000; Alarm.setRecurringAlarm("one second has passed", oneSecond); Alarm.setRecurringAlarm("five seconds have passed", fiveSeconds); Alarm.stopAlarms(); System.out.println("alarms stopped!"); timer.schedule(task, twentySeconds);