Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.

Slides:



Advertisements
Similar presentations
wwwcsif.cs.ucdavis.edu/~jacksoni
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Java threads Threaded class extends thread Synchronized class is a monitor Runnable interface gives thread methods All code is (C) Copyright 1999 by Deitel.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
2. Java and Concurrency Prof. O. Nierstrasz Selected material © Magee and Kramer.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Albert Johnson Molly Richardson Andrew Kruth.  Threads Runnable interface sleep()  GUIs repaint() paintComponent()
11-Jun-15 Producer-Consumer An example of using Threads.
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
Object-Oriented Software Engineering Concurrent Programming.
CP — Concurrent Programming 2. Java and Concurrency Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CSE S. Tanimoto Java Threads 1 Java Threads (Outline) Motivation The class Thread Example program: ThreadRace The Runnable interface Example: Clock.
16-Jun-15 Producer-Consumer An example of using Threads.
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
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.
28-Jun-15 Producer-Consumer An example of using Threads.
Lesson 9 Intro to Java Threads. What are threads?  Like several concurrent subprograms running within the same address space.  Within a program, individual.
ThreadThread Thread Basics Thread Synchronization Animations.
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-
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
„Threads”. Threads Threads - basics A thread is a single sequential flow of control within a program. A thread itself is not a program; it cannot run.
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.
Cosc 5/4730 A little on threads and Messages: Handler class.
תכנות מקבילי - I יישום ב- Java. References קורס "תכנות מקבילי ומבוזר", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Lecture 7. Java Threads Cheng-Chia Chen.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
Threads CSCE 190 – Java Instructor: Joel Gompert Wed, Aug 3, 2004.
Java Threads and higher level constructs for doing concurrent programming.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Chapter 6 (6.7 & 6.9 only) - Threads & Mutex Threads –A Thread is a basic unit of CPU utilization consisting of a program counter, register set and stack.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threads. Story so far  Our programs have consisted of single flows of control Flow of control started in the first statement of method main() and worked.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
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.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Multi-Threading in Java
Java Producer-Consumer Monitor From: Concurrent Programming: The Java Programming Language By Steven J. Hartley Oxford University Press, 1998.
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 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.
Component-Based Software Engineering Understanding Thread Safety Paul Krause.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Threads.
Многопоточность в Java
THREADS.
Threads Chate Patanothai.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
class PrintOnetoTen { public static void main(String args[]) {
Computer Science 2 06A-Java Multithreading
Threads in Java James Brucker.
Representation and Management of Data on the Internet
Threads.
Gentle Introduction to Threads
Presentation transcript:

Concurrency Java Threads

Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results before proceeding to the next step. Synchronization is necessary to avoid “race” conditions whenever a resource is shared. –variable –file or database –hardware

Basic steps in java Create a thread class In the thread class define the “run” method to define the parallel activity Create an object of the thread class you create. Call “start” on the thread object. Java will in turn call run when it starts up.

A simple example from sun.java.com public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } Create a thread class define the “run” method Create an object of the thread class Call “start”

Sample Output 0 Jamaica 0 Fiji 1 Fiji 1 Jamaica 2 Jamaica 2 Fiji 3 Fiji 3 Jamaica 4 Jamaica 4 Fiji 5 Jamaica 5 Fiji 6 Fiji 6 Jamaica 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica

Thread Life Cycle sun.java.com

Using timers indirectly sleep() function public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){ // the VM doesn't want us to // sleep anymore, // so get back to work } From an applet which uses stop() to set clockThread=null

Using timers directly import java.util.Timer; import java.util.TimerTask; public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); } Task scheduled. (5 seconds later) Time's up!

Producer Consumer revisited How does Java do it? (sun.java.com)

Producer Consumer issues Make sure there is something to consume Make sure there is room to produce Make sure that two entities don’t access the resource at the same time (race condition) How could you implement this in java?

Using threads (simple version) Make a thread which produces Make a thread which consumes results in -> parallel activity The resource is generically called a cubbyhole (place to put stuff) Each thread constructor gets –a cubbyhole to use and –an id

Producer public class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } }

Consumer public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); }

So what keeps them under control? Look at the cubbyhole

Cubbyhole public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try {wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); }

Main routine public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } Output Producer #1 put: 0 Consumer #1 got: 0 Producer #1 put: 1 Consumer #1 got: 1 Producer #1 put: 2 Consumer #1 got: 2 Producer #1 put: 3 Consumer #1 got: 3 Producer #1 put: 4 Consumer #1 got: 4 Producer #1 put: 5 Consumer #1 got: 5 Producer #1 put: 6 Consumer #1 got: 6 Producer #1 put: 7 Consumer #1 got: 7 Producer #1 put: 8 Consumer #1 got: 8 Producer #1 put: 9 Consumer #1 got: 9 Can you see how this locksteps? That’s not necessarily good!