Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.

Slides:



Advertisements
Similar presentations
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Advertisements

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.
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.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
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-
1 Handout 10 MULTI-THREADING BY GEORGE KOUTSOGIANNAKIS THIS DOCUMENT CAN NOT BE REPRODUCED OR DISTRIBUTED WITHOUT TH E WRITTEN PERMISSION OF THE AUTHOR.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
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.
Java Threads Representation and Management of Data on the Internet.
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.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
What Every Developer Should Know about the Kernel Dr. Michael L. Collard 1.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
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.
Java 3: Odds & Ends Advanced Programming Techniques.
Multi-Threading in Java
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.
THREAD MODEL.
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.
© 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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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.
Today Advanced JavaFX animation and 3D demos from Oracle. Threading. Winter 2016CMPE212 - Prof. McLeod1.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
More About 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.
ITEC324 Principle of CS III
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Java Threads (Outline)
Java Threads (Outline)
برنامه‌نویسی چندنخی Multi-Thread Programming
21 Threads.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads in Java Jaanus Pöial, PhD Tallinn, Estonia

Multi-threaded Programs Threads - processes inside one Java program (lightweight processes): parallel related to each other (share the same address space) cooperate using synchronization tools Critical section – part of a program that cannot be interrupted by other thread

In Java Class Thread (methods start, run, interrupt, join, yield, sleep, isAlive, setPriority, getPriority, setDaemon, ...) Interface Runnable (method run) Methods in class Object – wait, ..., notify, notifyAll synchronized blocks and methods priority system and timesharing Class Runtime (method exit) Class ThreadGroup

Thread States NEW - a thread that has not yet started is in this state. RUNNABLE - a thread executing in the Java virtual machine is in this state. BLOCKED - a thread that is blocked waiting for a monitor lock is in this state. WAITING – a thread that is waiting indefinitely for another thread to perform a particular action is in this state. TIMED_WAITING - a thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. TERMINATED - a thread that has exited is in this state.

Life Cycle of the Thread Create Process executed in thread is given as public void run() method that does not throw exceptions create a subclass of Thread and override the run() method use interface Runnable to create a new thread: Thread t = new Thread (runnableObject); run() method of the runnableObject is used Start t.start(); // run() is executed

Life Cycle of the Thread Thread runs until it: sleeps (sleep or wait is called, suspend and resume are now considered deprecated) waits for a lock to enter some critical section blocks for I/O (e.g. accept or read is called) gives up its time slot (yield) is preempted by higher priority thread is switched to another thread with the same priority in case of time-slicing scheme terminates

Life Cycle of the Thread Stop normal end – return from the run method deprecated stop method is called uncaught runtime exception occurs Sleep – go idle for given time (ms) Interrupt - wake up (InterruptedException is thrown); method interrupt() may not work correctly

Synchronization join – sleep until target thread finishes critical section in Java – synchronized block/method. Object lock (monitor) wait, notify, notifyAll wait – sleep and open the lock until notify is sent to this object (from some other thread) notifyAll – wakes all waiting threads, the winner starts execute, others go back sleeping

Priorities Each thread is given an integer priority, programmer can use constants Thread.NORM_PRIORITY, Thread.MAX_PRIORITY, Thread.MIN_PRIORITY Priority of a new thread is inherited from the thread that created it Threads with lower priority always wait for a thread with higher priority to terminate (whenever higher priority thread becomes runnable it preempts others)

Priorities Threads with the same priority: round robin – priority and synchronization rules apply but "parallel" execution caused by time sharing is not guaranteed time slicing – parallel or pseudo-parallel execution (all threads get chance) Thread might give up its time slot using the yield method

Priorities When a thread terminates: higher priority thread always takes over if there are no higher priority threads switch to the "next" runnable thread in this priority class if there are no runnable threads of current priority switch to the next lower priority class and choose a runnable thread

Priorities Usually increasing the priority of an "important" thread does NOT help in performance. Consider decreasing priorities of some other threads instead: getPriority and setPriority are the methods to use: Thread bgTask = new Thread (runnable_object); int prio = Thread.NORM_PRIORITY - (Thread.NORM_PRIORITY-Thread.MIN_PRIORITY)/2; bgTask.setPriority (prio); bgTask.start();

Server Threads and Thread Groups Server threads are "weak" – JVM terminates if all remaining threads are daemon threads Methods: setDaemon, isDaemon ThreadGroup is a set of threads (actually a tree because elements can be groups). Several operations can be applied to the whole group

Example – Producer/Consumer Producer-consumer task. We have a limited buffer, writer threads (producers) and reader threads (consumers). Rules: cannot read from the empty buffer – wait cannot write when the buffer is full – wait cannot change the buffer during reading - lock cannot change the buffer during writing - lock

Examples Threads.java Deadlock.java ConsProd5.java RunnableCP5.java ProdConSelective.java Pipes.java

Example – Runnable Applet Applet clock – Clock.java, clock.html