Threading Eriq Muhammad Adams J

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Practice Session 7 Synchronization Liveness Guarded Methods Model
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
1 Thread Pools Representation and Management of Data on the Internet.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
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.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
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-
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.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
More Multithreaded Programming in Java David Meredith Aalborg University.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Threads some important concepts Simon Lynch
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
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)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
© M. Winter COSC 3P91 – Advanced Object-Oriented Programming What is XML? XML stands for E X tensible M arkup L anguage XML is a markup language.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
1 Web Based Programming Section 8 James King 12 August 2003.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
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.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Thread and Memory Model
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Threading and Concurrency COM379T John Murray –
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multi-Threading in Java
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Threads and Multithreading. Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three general approaches:
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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.
CSCD 330 Network Programming
Multithreading / Concurrency
Multi Threading.
Threads Chate Patanothai.
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
CSCD 330 Network Programming
Lecture 19 Threads CSE /6/2019.
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threading Eriq Muhammad Adams J

* Thread ? * When to use threads * Creating Threads * Synchronization * Avoiding Deadlock * Demo * Reference

* A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

* If you have any time consuming tasks or procedures. * For example, use threads in these situations:  When loading lots of files from the local file system  When doing any network communication, such as sending high scores to a server  When doing any massive calculations, such as terrain generation

* Running threads : MyThread myThread = new MyThread(); myThread.start(); Thread myRunnable = new Thread(runnable); myRunnable.start(); * You’re able to create threads by extending Thread class or implement Runnable interface or using anonymous inner class. * Using anonymous inner class : new Thread(){ public void run(){ // do something here … } }.start();

* Implement Runnable interface : public class MyThread implements Runnable{ Public void run(){ // do something here … } * Extending Thread class : public class MyThread extends Thread { Public void run(){ // do something here … }

* Use join() method, If you want your current thread to wait until a thread is finished : myThread.join(); * Use sleep() method, If you want to make your thread sleep : Thread.sleep(100) // sleep thread in 100 ms

* Synchronization problem occurred when you’ve got multiple threads trying to access same objects or variables. Samples: public class Maze { private int playerX; private int playerY; public boolean isAtExit() { return (playerX == 0 && playerY == 0); } public void setPosition(int x, int y) { playerX = x; playerY = y; }

* Problem : Most of the time, this code works fine. But keep in mind that threads can be pre-empted at any time. Imagine this scenario, in which the player moves from (1,0) to (0,1): 1. Starting off, the object's variables are playerX = 1 and playerY = Thread A calls setPosition(0,1). 3. The line playerX = x; is executed. Now playerX = Thread A is pre-empted by Thread B. 5. Thread B calls isAtExit(). 6. Currently, playerX = 0 and playerY = 0, so isAtExit() returns true! In this scenario, the player is reported as solving the maze when it's not the case. To fix this, you need to make sure the setPosition() and isAtExit() methods can't execute at the same time.

* Solution : public class Maze { private int playerX; private int playerY; public synchronized boolean isAtExit() { return (playerX == 0 && playerY == 0); } public synchronized void setPosition(int x, int y) { playerX = x; playerY = y; } Or you can do like this : public void setPosition(int x, int y) { synchronized(this) { playerX = x; playerY = y; }

* Object synchronization : Object myLock = new Object(); synchronized (myLock) {... } * Local synchronization : public void myMethod() { synchronized(this) { // code that needs to be synchronized } // code that is already thread-safe }

* Using wait() and notify() : Case : Thread A waiting a message from Thread B // Thread A public void waitForMessage() { while (hasMessage == false) { Thread.sleep(100); } // Thread B public void setMessage(String message) { hasMessage = true; } It’s work but it’s chuncky

Solution : // Thread A public synchronized void waitForMessage() { try { wait(); } catch (InterruptedException ex) { } } // Thread B public synchronized void setMessage(String message){ notify(); }

* The wait() or wait(timeInMillis) method is used in synchronized blocks of code. When the wait() method executes, the lock is released and the thread waits to be notified. * The notify() method is also used in a synchronized block of code. The notify() method notifies one thread waiting on the same lock. If several threads are waiting on the lock, one of them is notified randomly. * notifyAll(), notifies all threads waiting on the lock, instead of just one. * don't synchronize a method that uses only local variables

* Deadlock is the result of two threads that stall because they are waiting on each other to do something. * Consider this example: 1. Thread A acquires lock Thread B acquires lock Thread B waits for lock 1 to be released. 4. Thread A waits for lock 2 to be released. * Please read article at :

* Demo available in ThreadingDemo.zipThreadingDemo.zip

* David Brackeen, Developing Games in Java, New Riders Publishing, 2003