Concurrency and Java Programming
|
|
- Silvia Dalton
- 5 years ago
- Views:
Transcription
1 Concurrency and Java Programming What is Concurrent Programming? Concurrent programming involves using features of the Java VM that allow parts of your program to run in parallel with each other. This involves creating objects that implement threading and executing such objects in parallel. Normally, when you write a program using methods, and you execute a method, the program waits for the method to return before continuing. A thread would be like a method that, when called, starting running and your main program continues to execute after calling the method. The main program does not have to wait for the method to finish before continuing. The main reason for creating concurrent programs in Java is to solve specific problems. For example, a GUI program may want to read/write objects to a database but not perform such IO while the user is working with the GUI components. Another application would be network programming. A Server program designed to handle multiple incoming connections will likely need to create multiple threads to handle such connections. Processes and Threads There is a difference between a Process and a Thread. Typically, Processes are used by operating systems to perform concurrent actions. Windows has a print spooler process that will operate at the same time foreground programs are running. This allows you to print in the background. However, a Process normally has its own memory structure and stack. The Operating System manages such processes by separating them from each other so if a process crashes it won t affect other processes. The way such separation is done is by isolating processes in their own memory space. If a process needs to communicate with another process, it would use some operating system method such as inter-process communication pipelines. Threads are a lightweight type of Processes. A Thread exists within a Process. Threads share a common memory structure and stack and are separated by the virtual machine (this is why you see Threading more often in languages like Java and C#). Threads can more easily communicate with each other by sending messages to another named Thread. Creating and Using a Thread In Java, there is a Thread class which is used to create concurrent objects. This Thread class can be used in two ways; by inheriting your class from the Thread base class, or by using an Interface and causing your object to be executed from outside. The primary difference between these two methods of creating runnable objects is one of design. Using the Thread as a base class implies that your class is-a type of Thread. This inheritance requirement involves redesigning your class inheritance chain. A second way is to apply an interface to your class and write the methods need to start the object. You would then use an Executor class to start your object running. This method does not require that your class inherit from the base class Thread but that it implement an interface. This method is good for situations where you want to retrofit concurrency onto an existing class. Inheriting from Thread Class: In this method you create a class that extends the Thread class. This base class requires that your class override the method named run(). This is the method that will be executed when your object starts. When this method completes then your object stops running. The following simple program creates a class that extends the Thread class:
2 import java.util.*; import java.io.*; public class MainProgram public static void main(string[] args) MyThreadClass c1 = new MyThreadClass("Frank", 5000); MyThreadClass c2 = new MyThreadClass("Donna", 8000); c1.start(); c2.start(); while (true) if( c1.getnumlives() == 0 && c2.getnumlives()==0) break; System.out.println("All done"); class MyThreadClass extends Thread private String name; private int pausenum; private int numlives; public MyThreadClass(String n, int p) name = n; pausenum = p; numlives = 10; public int getnumlives() return numlives; public void run() while (numlives > 0) System.out.println("Hello: I am " + name); numlives--; try Thread.sleep(pausenum); catch (InterruptedException e) e.printstacktrace();
3 The class MyThreadClass extends Thread. The only method in Thread that must be overridden in the inheriting class is run() which is public and with returns void. The MyThreadClass takes two values for the Constructor, the thread object name and the number of pausing milliseconds. Each thread object will print its own name after pausing the specified number of milliseconds. Each thread object is also set with 10 lives. The Constructor for these Thread objects just sets these values. Once a thread object is created (in main() ) it must be started. This second step is necessary in order to kick-start the thread. When the start() method is called on the Thread object it initiates the run() method. You never directly call run() because the Thread class must initialize internal structures. The Thread class as defined contains a method to return the number of lives. Notice how the run() method is actually a loop using the while() structure. Inside the loop the run() method looks like: public void run() while (numlives > 0) System.out.println("Hello: I am " + name); numlives--; try Thread.sleep(pausenum); catch (InterruptedException e) e.printstacktrace(); While the number of lives in the Thread object are greater than zero then the method prints the name, reduces the number lives, and sleeps for the specified milliseconds. Notice that the method: Thread.sleep( xxx ) Is used to pause execution of the thread. This is a static method in the base Thread class and it must be called in a try/catch block. Using the Runnable Interface: A second way to create a concurrent object is to use the Runnable interface. This is an interface that is applied to a class. Once applied, the runnable object is passed to a new Thread object and the Thread object uses start(). The previous program has been rewritten to use the Runnable Interface: import java.util.*; import java.io.*; public class MainProgram public static void main(string[] args)
4 MyThreadClass c1 = new MyThreadClass("Frank", 5000); MyThreadClass c2 = new MyThreadClass("Donna", 8000); Thread x1 = new Thread(c1); x1.start(); Thread x2 = new Thread(c2); x2.start(); while (true) if( c1.getnumlives() == 0 && c2.getnumlives()==0) break; System.out.println("All done"); class MyThreadClass implements Runnable private String name; private int pausenum; private int numlives; public MyThreadClass(String n, int p) name = n; pausenum = p; numlives = 10; public int getnumlives() return numlives; public void run() while (numlives > 0) System.out.println("Hello: I am " + name); numlives--; try Thread.sleep(pausenum); catch (InterruptedException e) e.printstacktrace();
5 In this program everything looks almost the same except the MyThreadClass implements an Interface named Runnable. This Interface requires that the run() method be used. An instance of this Interface class is then created and passed into the constructor for a new Thread object. This object is then used to start the object. MyThreadClass c1 = new MyThreadClass("Frank", 5000); MyThreadClass c2 = new MyThreadClass("Donna", 8000); Thread x1 = new Thread(c1); x1.start(); Thread x2 = new Thread(c2); x2.start(); This may seem like a lot of extra work, but it does allow you to quickly modify an existing class by adding the Runnable interface (even if the class already has an Interface and is inherited from another class) and then writing a run() method. Starting this object can also be simplified. Notice that the Thread objects x1 and x2 are only used to start the runnable object. You can simply the above code with: (new Thread(c1)).start(); (new Thread(c2)).start(); Synchronization Threading often results in objects executing at the same time but referencing shared resources. For example, two or more objects may reference a shared object and both attempt to use the object. When this happens the shared object may not have the results that each thread object expects. For example: import java.util.*; import java.io.*; public class MainProgram public static void main(string[] args) TMsg m = new TMsg(); MyThreadClass c1 = new MyThreadClass("Frank", 5000, m); MyThreadClass c2 = new MyThreadClass("Donna", 100, m); (new Thread(c1)).start(); (new Thread(c2)).start(); while (true) if( c1.getnumlives() == 0 && c2.getnumlives()==0) break;
6 System.out.println("All done"); class TMsg private int count; public void inc() count++; public void dec() count--; public int getc() return count; class MyThreadClass implements Runnable private String name; private int pausenum; private int numlives; private TMsg mm; public MyThreadClass(String n, int p, TMsg m) name = n; pausenum = p; numlives = 10; mm = m; public int getnumlives() return numlives; public void run() while (numlives > 0) System.out.printf("Current value is %s for %d ",name,mm.getc()); mm.inc(); System.out.printf("Hello: I am %s - I read %d \n",name,mm.getc()); numlives--; try Thread.sleep(pausenum); catch (InterruptedException e) e.printstacktrace();
7 In this example, an object of the class TMsg is created and given to each thread object. Since this is an object what is given to each Thread object is a pointer. Each Thread object uses this TMsg object to call an increment method. These methods will make changes to the object. The problem is that other Thread objects are also making calls to the inc() method and the getc() methods. While one Thread object increments the shared value, the other may decrement. In order to ensure that the method, when it is called, is locked for a specific thread, the term synchronized is used to identify the method. class TMsg private int count; public synchronized void inc() count++; public synchronized void dec() count--; public synchronized int getc() return count; This term causes the Threading code to lock the method and prevent other Threads from accessing the method until it is done. Sample Program import java.util.*; import java.io.*; import java.io.*; public class MainProgram public static void main(string[] args) // make some books ArrayList<BookClass> myarr = new ArrayList<BookClass>(); myarr.add( makebook("isb111","book1","author1",45.55,2001) ); myarr.add( makebook("isb222","book2","author2",23.33,2000)); myarr.add(makebook("isb333","book3","author3",54.44,1999)); myarr.add(makebook("isb444","book4","author4",65.55,2000)); // make a book writer BookWriter bkwtr = new BookWriter(); bkwtr.setfile("mybooks.txt"); bkwtr.setarray(myarr); (new Thread(bkwtr)).start(); while( bkwtr.getflag() == false) System.out.println("Waiting"); System.out.println("Done with program");
8 public static BookClass makebook(string isbn, String title, String auth, double price, int pr) BookClass bk = new BookClass(); bk.setisbn(isbn); bk.settitle(title); bk.setauthor(auth); bk.setprice(price); bk.setpubdate(pr); return bk; class BookClass private String isbn; private String title; private String author; private double price; private int pubdate; public String gettitle() return title; public void settitle(string title) this.title = title; public String getauthor() return author; public void setauthor(string author) this.author = author; public double getprice() return price; public void setprice(double price) this.price = price; public int getpubdate() return pubdate;
9 public void setpubdate(int pubdate) this.pubdate = pubdate; public String getisbn() return isbn; public void setisbn(string isb) isbn = isb; class BookWriter implements Runnable private ArrayList<BookClass> bkarray; private BufferedWriter wtr; private boolean finished; public BookWriter() bkarray = null; wtr = null; finished = false; public boolean getflag() return finished; public void setfile(string fn) try wtr = new BufferedWriter( new FileWriter(fn) ); catch (IOException e) System.out.println("Error creating output file"); public void setarray(arraylist<bookclass> bk) bkarray = public void run() if( wtr==null)
10 finished=false; return; try for (BookClass bk: bkarray) // make output string String fmt = String.format("%s,%s,%s,%f,%d\n", bk.getisbn(),bk.getauthor(), bk.gettitle(),bk.getprice(),bk.getpubdate()); wtr.write(fmt); // pause for effect Thread.sleep(3000); wtr.close(); finished=true; catch (IOException e) System.out.println("Error writing books"); catch (InterruptedException e) System.out.println("Error in write thread"); wtr = null; This program creates a BookClass that stores book information. This class is used to create an array list of objects. A BookWriter class is also defined. This class uses the Runnable interface and therefore must contain a run() method. This method uses the internal ArrayList of book objects and writes each object out to an external file. There is a 3 second pause after each write. The main program will start this BookWriter object going with the command: (new Thread(bkwtr)).start(); Notice that a thread object is never saved and it is only created long enough to start the bookwriter object. The main program contains a loop that runs in parallel to the book writer object. This loop is: while( bkwtr.getflag() == false) System.out.println("Waiting");
11 The bookwriter object contains a flag (boolean) that is initially set to false. When the flag is flipped to true then the run() method has finished. This is a way to communicate from inside a runnable object; by using a flag. Using Threading The main areas where Thread based programs are used are in GUI programs and in networking programs. In the Networking lecture a sample program will be created that also uses Threads.
Multiplayer Game Programming 2/26
Multiplayer Game Programming 2/26 1. Turn off Windows Firewall 2. Download and install Python and Notepad++ a. Python.org downloads/python/install b. Notepad-plus-plus.org download/install 3. Download
More informationThreads Chate Patanothai
Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?
More informationMultiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)
M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but
More informationReading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.
Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)
More informationCS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03
CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption
More informationCS 351 Design of Large Programs Threads and Concurrency
CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level
More informationAdvanced Programming Methods. Lecture 6 - Concurrency in Java (1)
Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want
More informationContents. 6-1 Copyright (c) N. Afshartous
Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004
More informationCMSC 132: Object-Oriented Programming II. Threads in Java
CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files
More informationCrash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++
Crash Course in Java Netprog: Java Intro 1 Why Java? Network Programming in Java is very different than in C/C++ much more language support error handling no pointers! (garbage collection) Threads are
More informationJava Threads and intrinsic locks
Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object
More informationMultithreaded Programming
Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes
More information7. MULTITHREDED PROGRAMMING
7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread
More informationTHREADS AND CONCURRENCY
THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on
More informationConcurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen
Concurrency http://csunplugged.org/routing-and-deadlock CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Multi-threaded programs Multiple simultaneous paths of execution Seemingly
More informationProgramming Language Concepts: Lecture 11
Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]
More informationProblems with Concurrency. February 19, 2014
with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings
More informationJava Threads. COMP 585 Noteset #2 1
Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the
More informationConcurrency. Fundamentals of Computer Science
Concurrency http://csunplugged.org/routing-and-deadlock Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually
More informationJava s Implementation of Concurrency, and how to use it in our applications.
Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video
More informationNote: Each loop has 5 iterations in the ThreeLoopTest program.
Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and
More informationLecture 9: Introduction to Monitors
COMP 150-CCP Concurrent Programming Lecture 9: Introduction to Monitors Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 14, 2008 Abstracting Locking Details Recall our discussion
More informationJava Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently
Java Threads Rui Moreira Links: http://java.sun.com/docs/books/tutorial/essential/threads/index.html Thread Thread comprises 3 parts: n Leightwheight process n Single and sequential flow of control within
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and
More informationMultiThreading. Object Orientated Programming in Java. Benjamin Kenwright
MultiThreading Object Orientated Programming in Java Benjamin Kenwright Outline Review Essential Java Multithreading Examples Today s Practical Review/Discussion Question Does the following code compile?
More informationJava Threads. Written by John Bell for CS 342, Spring 2018
Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.
More informationExercise Session Week 8
Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void
More informationMichele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues
Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Concurrency Issues Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core)
More informationRobotics and Autonomous Systems
1 / 38 Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 2 / 38 Today Some more programming techniques that
More informationConcurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17
Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,
More informationTHREADS AND MULTITASKING ROBOTS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 comp329-2013-parsons-lect10 2/37 Today Some more programming techniques that will be helpful
More informationROBOTICS AND AUTONOMOUS SYSTEMS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 THREADS AND MULTITASKING ROBOTS comp329-2013-parsons-lect10 2/37 Today Some more programming
More informationDefinition: A thread is a single sequential flow of control within a program.
What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.
More informationThreads, Concurrency, and Parallelism
Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start
More information1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax
Lab report Project 3 Mihai Ene I have implemented the solution in Java. I have leveraged its threading mechanisms and concurrent API (i.e. concurrent package) in order to achieve the required functionality
More informationCISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications
CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics
More informationCS193k, Stanford Handout #8. Threads 3
CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current
More informationExercise Session Week 8
Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones
More informationCS 556 Distributed Systems
CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 5 problems on the following 7 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet
More informationMultithreading using Java. Dr. Ferdin Joe John Joseph
Multithreading using Java Dr. Ferdin Joe John Joseph 1 Agenda Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing Shared Resources Synchronisation Assignment
More informationTHREADS & CONCURRENCY
27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late
More informationUnit 4. Thread class & Runnable Interface. Inter Thread Communication
Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more
More informationCS 159: Parallel Processing
Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level
More informationProgram #3 - Airport Simulation
CSCI212 Program #3 - Airport Simulation Write a simulation for a small airport that has one runway. There will be a queue of planes waiting to land and a queue of planes waiting to take off. Only one plane
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationMultiprocessing Threads/Lightweight objects Thread methods Concurrency Issues
Concurrency Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues What is program execution? In order to run, a program must be loaded into memory and given an initial state. Code
More informationG51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions
G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]
More informationJava Barrier Synchronizers: CountDownLatch (Part 1)
Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,
More informationLecture 35. Threads. Reading for next time: Big Java What is a Thread?
Lecture 35 Threads Reading for next time: Big Java 21.4 What is a Thread? Imagine a Java program that is reading large files over the Internet from several different servers (or getting data from several
More informationCS11 Java. Fall Lecture 7
CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)
More informationComputation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes
More informationMultitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit
Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking
More informationJAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling
JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;
More informationCMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012
CMPSCI 187: Programming With Data Structures Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012 Concurrency and a Case Study Concurrency and Threads Example: Counter, Increase,
More informationChair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova
Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public
More informationConcurrency Quiz: Java Threads
Concurrency Quiz: Java Threads First name, last name:................................................................. Background information In this part of the quiz, we would like to collect some information
More informationCS180 Review. Recitation Week 15
CS180 Review Recitation Week 15 Announcement Final exam will be held on Thursday(12/17) 8:00~10:00 AM The coverage is comprehensive Project 5 is graded. Check your score in Blackboard. Classes and Methods
More informationF. Tip and M. Weintraub CONCURRENCY
F. Tip and M. Weintraub CONCURRENCY SHARED-MEMORY CONCURRENCY threads execute concurrently threads communicate values via shared memory synchronization using locks 2 PITFALLS data races atomicity violations
More informationThreads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II
Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running
More informationBugs in software. Using Static Analysis to Find Bugs. David Hovemeyer
Bugs in software Programmers are smart people We have good techniques for finding bugs early: Unit testing, pair programming, code inspections So, most bugs should be subtle, and require sophisticated
More informationCOMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]
COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing
More informationWeek 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand
More informationJAVA EXAMPLES - SOLVING DEADLOCK
JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following
More informationConcurrent Computing CSCI 201 Principles of Software Development
Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking
More informationUser Space Multithreading. Computer Science, University of Warwick
User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing
More informationMultiprocessing Threads/Lightweight objects Thread methods Concurrency Issues
Concurrency Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues What is program execution? In order to run, a program must be loaded into memory and given an initial state. Code
More informationModule - 4 Multi-Threaded Programming
Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is
More informationJava Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency
Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread
More informationAmity School of Engineering
Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple
More informationUnit - IV Multi-Threading
Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first
More informationThreads and Parallelism in Java
Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program
More informationQuestion Points Score Total 100
Midterm Exam #1 CMSC 433 Programming Language Technologies and Paradigms Spring 2014 March 13, 2014 Guidelines Put your name on each page before starting the exam. Write your answers directly on the exam
More informationOverview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms
More informationCmpSci 187: Programming with Data Structures Spring 2015
CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more
More informationMultithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science
Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the
More informationGlobalLogic Technical Question Paper
GlobalLogic Technical Question Paper What is the output of the following code when compiled and run? Select two correct answers. public class Question01 { public static void main(string[] args){ int y=0;
More informationINF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.
INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients
More informationTHREADS & CONCURRENCY
4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7
More informationAnimation Part 2: MoveableShape interface & Multithreading
Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply
More information40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the
Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No
More informationMultithreading Pearson Education, Inc. All rights reserved.
1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads
More informationMidterm assessment - MAKEUP Fall 2010
M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization
COMP 213 Advanced Object-oriented Programming Lecture 23 Shared Variables and Synchronization Communicating Threads In the previous lecture, we saw an example of a multi-threaded program where three threads
More informationECE462Exam3. 08:10-09:20AM, November 20, 2009
ECE462Exam3 08:10-09:20AM, November 20, 2009 IcertifythatIwillnotreceivenorprovideaidtoanyotherstudentforthisexam. Signature: Youmustsignhere.Otherwise,theexamisnotgraded. This exam is printed double sides.
More informationMultithreaded Programming
core programming Multithreaded Programming 1 2001-2003 Marty Hall, Larry Brown http:// 2 Multithreaded Programming Agenda Why threads? Approaches for starting threads Separate class approach Callback approach
More informationThreads and Java Memory Model
Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing
More informationMultiple Inheritance. Computer object can be viewed as
Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.
More informationJAVA Programming Language Homework VI: Threads & I/O
JAVA Programming Language Homework VI: Threads & I/O ID: Name: 1. When comparing java.io.bufferedwriter to java.io.filewriter, which capability exists as a method in only one of the two? A. Closing the
More informationMichele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Threads
Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Threads Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationLecture 4 JAVA (46-935) Somesh Jha
Lecture 4 JAVA (46-935) Somesh Jha 1 Inner Classes Flashback totheabstracttermstructure class. There was a SlowYieldVolObject which computed: { (i = 0) Dierence between computed yield and the market yield
More informationConcurrent, Real-Time and Distributed Programming in Java
Concurrent, Real-Time and Distributed Programming in Java FOCUS SERIES Jean-Charles Pomerol Concurrent, Real-Time and Distributed Programming in Java Threads, RTSJ and RMI Badr Benmammar First published
More informationOutline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)
i219 Software Design Methodology 10. Multithreaded programming Kazuhiro Ogata (JAIST) Outline of lecture 2 Thread Race condition Synchronization Deadlock Bounded buffer problem Thread (1) 3 Units of execution.
More informationThreads in Java (Deitel & Deitel)
Threads in Java (Deitel & Deitel) OOutline 1 Introduction 1 Class Thread: An Overview of the Thread Methods 1 Thread States: Life Cycle of a Thread 1 Thread Priorities and Thread Scheduling 1 Thread Synchronization
More informationM257 Past Paper Oct 2007 Attempted Solution
M257 Past Paper Oct 2007 Attempted Solution Part 1 Question 1 The compilation process translates the source code of a Java program into bytecode, which is an intermediate language. The Java interpreter
More informationThreads. Fundamentals of Computer Science
Threads Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at the same time (multiple cores) Why? Get work
More informationThe Proxy Pattern. Design Patterns In Java Bob Tarr
The Proxy Pattern Intent Provide a surrogate or placeholder for another object to control access to it Also Known As Surrogate Motivation A proxy is a person authorized to act for another person an agent
More informationThreads & Concurrency
Threads & Concurrency Lecture 24 CS2110 Spring 2017 Due date of A7 Due d About A5-A6 2 We have changed the due date of A7 Friday, 28 April. But the last date to submit A7 remains the same: 29 April. We
More information