Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.

Slides:



Advertisements
Similar presentations
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
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.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 Java Threads and Synchronization Review Modified from slides taken from
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)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
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.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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.
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.
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.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
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
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
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.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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 (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.
Distributed and Parallel Processing George Wells.
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Multithreaded Programming in Java
More About Threads.
Threads Chate Patanothai.
Multithreading.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
برنامه‌نویسی چندنخی Multi-Thread Programming
21 Threads.
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Threads Lilin Zhong

Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems and solutions

Java Threads 5. Signaling with wait, notify, and notifyAll 6. When threads freeze: deadlock 7. Scheduling: problems and solutions 8. The end of the thread

Why Thread? Thread Java threads Example: Stockbroker

Stockbroker Download last stock prices Check prices for warnings Analyze historical data for company X Time

New Threads Public void run(); ProcessThreads

New Thread Creating a thread by: 1. Extending the Thread class 2. Implementing the Runnable interface

Creating a Thread by Extending the Thread Class Declaring public class MyThread extends Thread{ public void run(){ // Your instructions here } Instantiating - MyThread testThread=new MyThread();

By Implementing the Runnable Interface Defining - public class MyRunnable implements Runnable{ public void run(){ // Your instructions here} } Instantiating - MyRunnable firstRunnable = new MyRunnable; - Thread testThread = new Thread (firstRunnable);

Starting an Instance of a Thread testThread.start();

Java Threads 1. New threads 2. Threads in the running state

Threads in the Running State Execute run methods concurrently; Cooperate, share resources, compete; Take turns to run; Switch.

Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions

Sleeping Threads and Interruptions -Thread.sleep(long n); e.g. Thread.sleep(5*60*1000); -sleepingThread.interrupt();

Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems and solutions

Concurrent Access Problems and Solutions - e.g. i++; - bring “i” to register; - add 1 to register; - store register onto “i”. ways to solve the problems: Using volatile to transmit single variables between two threads. Using synchronized to transmit groups of variables among multiple threads.

Volatile V setget 1V(1) copy Time V(2)2 copy V V 12 public class transfer{ private Object value; public set(value){ this.value=value; } public Object get(){ return value; } } set get

Volatile V V Time 1 2 set get V12 public class transfer{ private volatile Object value; public set(value){ this.value=value; } public Object get(){ return value; } } setget

Synchronized Time Thread 1Thread 2 Current ThreadWaiting Thread L1 Synchronized block

Synchronized public class StatusInfo{ private float temperature, pressure, nitroConcentration; public synchronized void update (float temperature, float pressure, float nitroConcentration){ this.temperature=temperature; this.pressure=pressure; this.nitroConcentration=nitroConcentration; } public synchronized void analyze(){ if (isDangerousCombination (temperature, pressure, nitroConcentration); stopManufacture(); }

Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems and solutions 5. Signaling with wait, notify, and notifyAll

Signaling With Wait, Notify, and notifyAll Using wait and notify by two interdependent threads Using notifyAll when many threads may be waiting

Signaling With Wait, Notify, and notifyAll void wait() Waits for a condition to occur void notify() Notifies a thread that is waiting for a condition that the condition has occurred void notifyAll() Notifies all the threads waiting for a condition that the condition has occurred

Wait, Notify synchronized(this){ try{ wait(); }catch(InterruptedException e){} } synchronized(this){ notify(); } L1 Time Current Thread Waiting Thread L1

NotifyAll Public class Multiplewriters{ private Object item; public synchronized void write(Object o) throws InterruptedException{ while (item!=null) wait(); item=o; notify(); // single writer, notifying one reader // is sufficient }

NotifyAll Public synchronized Object read() throws InterruptedException { while (item==null) wait(); Object myItem=item; item=null; notifyAll(); // multiple readers, // notifyAll ensures writer notification return myItem; }

Java Threads 6. When threads freeze: deadlock

When Threads Freeze: Deadlock Time Thread 1Thread 2 L1 Current Thread Waiting Thread L2 L1 L2 Blocks here waiting for L1 Blocks here waiting for L2

Java Threads 6. When threads freeze: deadlock 7. Scheduling: problems and solutions

Scheduling: Problem and Solution When does the current thread lose its turn at CPU: Yield()  Thread.yield(); //will give up the turn on the CPU Sleep, wait, or blocked by I/O Priority “time-slicing”

Scheduling: Problem and Solution Which thread will be the next to execute? Specify the priority of threads  setPriority(int n) n=1 to 10 Main5  Static final ints: MIN_PRIORITY1 NORM_PRIORITY5 MAX_PRIORITY10

Java Threads 6. When threads freeze: deadlock 7. Scheduling: problems and solutions 8. The end of the thread

The End of The Thread System.exit(n) Returning from run method Throwing an unchecked exception Blocked by I/O others

Summary How create threads by extending Thread and by implementing Runnable, and how to start them. How to share information effectively, threads use synchronized blocks of code.

Summary How to coordinate activity through time, using wait/notify model. What different thread states ( new, dead) are, when threads go in and out of sleeping, waiting, blocking on I/O, and acquiring lock states.

Example: Neko Neko12.java Neko.html

References: Java Threads, 2nd Edition, Scott Oaks & Henry Wong Multithreaded programming with Java technology, Bil Lewis & Daniel J. Berg Teaching yourself Java 1.2 in 21 days, Laura Lemay & Rogers Cadenhead Java How to program, third edition, Deitel & Deitel Java 2 certificate