Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject.

Slides:



Advertisements
Similar presentations
50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Programming Language Semantics Java Threads and Locks Informal Introduction The Java Specification Language Chapter 17.
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-
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Ryerson University CPS Distributing Computing with Java.
Java Programming: Advanced Topics
Critical Reference An occurrence of a variable v is defined to be critical reference: a. if it is assigned to in one process and has an occurrence in another.
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)
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
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.
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.
Multithreading Chapter Introduction Consider ability of human body to ___________ –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.
Threads Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment?
Java Thread and Memory Model
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Java 3: Odds & Ends Advanced Programming Techniques.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
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.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
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.
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.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Multithreading.
Java Based Techhnology
Multithreading.
Real Time Java : Synchronization
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject Oriented Language  Everything is an object  Common base class xSimplicity

Java zJava features  Automatic garbage collection  Nice exception handling  Object hierarchy  Polymorphic data structures  Wrapper classes  Memory management  Cloning

Java API Packages package java.applet package java.awtjava.appletjava.awt package java.awt.datatransfer package java.awt.eventjava.awt.datatransfer java.awt.event package java.awt.image package java.beansjava.awt.imagejava.beans package java.io package java.langjava.iojava.lang package java.lang.reflect package java.mathjava.lang.reflectjava.math package java.net package java.securityjava.netjava.security package java.security.acl package java.security.interfacesjava.security.acl java.security.interfaces package java.sql package java.textjava.sqljava.text package java.util package java.util.zipjava.utiljava.util.zip

Java - Sequential Execution (Example 1) /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. }

Java - Sequential Execution (Example 2) public static void main( String[ ] args ){ // Web page grep if (args.length != 2){ // Input arguments: URL, text System.out.println("Find String URL"); return; } String str = args[0]; try { URL url = new URL(args[1]); // Open connection, and use page InputStream in = url.openStream(); // as a stream StreamTokenizer tokens = new StreamTokenizer(in); int matchCount = 0; // Count the tokens which match the while(tokens.nextToken() != StreamTokenizer.TT_EOF) { // input stream if (tokens.ttype == StreamTokenizer.TT_WORD) if (str.equalsIgnoreCase(tokens.sval)) // Ignore case in looking matchCount++; // for matches } System.out.println(matchCount + " matches of " + str + " found at " + args[1]); } catch( MalformedURLException mue) { // Errors if URL is bad, or System.out.println("Bad URL"); // problems with input } catch(IOException ioe) { System.out.println("IO Error"); }

Locks and Synchronization (1) zA variable is any location within a Java program that may be stored into zVariables are kept in a main memory that is shared by all threads zEvery thread has a working memory in which it keeps its own working copy of variables that it must use or assign zThe main memory contains the master copy

Locks and Synchronization (2) zJava providing mechanisms for synchronizing the concurrent activity of threads zJava uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor zThe behavior of monitors is explained in terms of locks

Locks and Synchronization (3) zA lock associated with every object zThreads may compete to acquire a lock zNo separate lock and unlock actions; instead, they are implicitly performed by high-level constructs zJava VM does provide separate monitorenter and monitorexit instructions

Synchronized statement zAcquires a mutual-exclusion lock on behalf of the executing thread zFirst computes a reference to an object zThen it attempts to perform a lock action on that object and does not proceed further until the lock action has successfully completed zAfter the lock action has been performed, the body of the synchronized statement is executed zIf execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed

Synchronized method (1) zAgain, first computes a reference to an object zAutomatically attempt to perform a lock action zBody of method is not executed until the lock action has successfully completed zIf the method is an instance method, it locks the lock associated with the instance zIf the method is static, it locks the lock associated with the class object that represents the class zIf execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed

Synchronized method (2)

Synchronized method (3) zThe methods wait, notify, notifyAll of class zobject support an efficient transfer of control from one thread to another. Instead of “spinning”, a thread can suspend itself using wait until such time as another thread awakens it using notify zEspecially appropriate in situations where threads have a producer- consumer relationship (actively cooperating on a common goal) rather than a mutual exclusion relationship (trying to avoid conflicts while sharing a common resource) zIf two or more concurrent threads act on a shared variable, there is a possibility that the actions on the variable will produce timing- dependent results - “race condition”

Class java.lang.Object

Class java.lang.Thread zExtends java.lang.Object zMethods ycurrentThread() Returns a reference to the currently executing thread objectcurrentThread ygetName() Returns this thread's namegetName ysetName(String) Changes the name of this thread to be equal to the argument namesetName ygetPriority() Returns this thread's prioritygetPriority  setPriority(int) Changes the priority of this thread. setPriority  run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns run ydestroy() Destroys this thread, without any cleanupdestroy

Class java.lang.Thread (cont’d) yinterrupt() Interrupts this threadinterrupt yinterrupted() Tests if the current thread has been interruptedinterrupted yresume() Resumes a suspended threadresume ysleep(long) Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.sleep ystart() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.start ystop() Forces the thread to stop executing.stop ystop(Throwable) Forces the thread to stop executing.stop ysuspend() Suspends this thread.suspend  yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute. yield

Creating a New Thread (1) zMethod One: Declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started zExample:

Creating a New Thread (2)  Method Two: D eclare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started zExample: