Advanced Object-oriented Programming
|
|
- Jocelyn Daniels
- 5 years ago
- Views:
Transcription
1 COMP 213 Advanced Object-oriented Programming Lecture 21 Concurrency
2 What is Concurrency? Concurrency is when two or more programs execute at the same time, either: sharing the same processor (multi-threading), or on different processors; these may be in the same machine (multi-processor architecture), or in different machines (distributed computation).
3 What Use is Concurrency? Reasons for using concurrency include: to perform a computation more quickly (usually using many processors), or to allow users to interact with programs while a computation is in progress. (E.g., allow more than one client to access a server at a time; or, allow users to interact with a GUI while some computation proceeds,)
4 Concurrency Comes at a Cost For both kinds of concurrency, there are overheads: communication between different processors takes time (and the more processors, the higher the costs) to share one processor among many programs, one program has to be chosen to run; when its time is up, it has to be stopped, its current state stored, another program chosen to run, and its previous state restored all of which takes time.
5 Multithreading We will concentrate on multithreading: where several programs run on one processor. This is familiar from window managers that typically allow computer users to have several windows on the screen at once, each running a different program (and usually with several other programs running in the background).
6 Multithreading Multithreading is typically implemented by time-slicing: one program is chosen to run for a certain amount of time (a quantum ) the period is not determined by the program; once this amount of time has passed, the program is stopped and the values of its variables are stored in memory; another program is chosen to run, and the values of its variables are restored from memory; the program runs, and this procedure is repeated for as long as there are programs left to run.
7 Multithreading Multithreading is typically implemented by time-slicing: one program is chosen to run for a certain amount of time (a quantum ) the period is not determined by the program; once this amount of time has passed, the program is stopped and the values of its variables are stored in memory; another program is chosen to run, and the values of its variables are restored from memory; the program runs, and this procedure is repeated for as long as there are programs left to run.
8 Multithreading Multithreading is typically implemented by time-slicing: one program is chosen to run for a certain amount of time (a quantum ) the period is not determined by the program; once this amount of time has passed, the program is stopped and the values of its variables are stored in memory; another program is chosen to run, and the values of its variables are restored from memory; the program runs, and this procedure is repeated for as long as there are programs left to run.
9 Multithreading Multithreading is typically implemented by time-slicing: one program is chosen to run for a certain amount of time (a quantum ) the period is not determined by the program; once this amount of time has passed, the program is stopped and the values of its variables are stored in memory; another program is chosen to run, and the values of its variables are restored from memory; the program runs, and this procedure is repeated for as long as there are programs left to run.
10 Multithreading Multithreading is typically implemented by time-slicing: one program is chosen to run for a certain amount of time (a quantum ) the period is not determined by the program; once this amount of time has passed, the program is stopped and the values of its variables are stored in memory; another program is chosen to run, and the values of its variables are restored from memory; the program runs, and this procedure is repeated for as long as there are programs left to run.
11 Multithreading Note that this switching between programs is not determined by the programs that are running, but by the time slicer : this might be, e.g., the window manager, the operating system, or the implementation of the Java interpreter. Since we are interested in multithreaded Java programs, we ll be concerned with time slicing as it is implemented by the Java interpreter.
12 Multithreading Note that this switching between programs is not determined by the programs that are running, but by the time slicer : this might be, e.g., the window manager, the operating system, or the implementation of the Java interpreter. Since we are interested in multithreaded Java programs, we ll be concerned with time slicing as it is implemented by the Java interpreter.
13 How to Write Concurrent Programs? At its simplest, concurrency can be achieved by writing two or more programs, and then starting them. Java supports this simplest form of concurrency. A Java programmer can simply write two or more programs, and then start them. Of course, since we re talking about Java, these programs have to be contained in some class we ll look at the classes (and interfaces) needed for this, and the support that Java provides for managing the complexities that arise from running several programs at the same time.
14 How to Write Concurrent Programs? At its simplest, concurrency can be achieved by writing two or more programs, and then starting them. Java supports this simplest form of concurrency. A Java programmer can simply write two or more programs, and then start them. Of course, since we re talking about Java, these programs have to be contained in some class we ll look at the classes (and interfaces) needed for this, and the support that Java provides for managing the complexities that arise from running several programs at the same time.
15 How to Write Concurrent Programs? At its simplest, concurrency can be achieved by writing two or more programs, and then starting them. Java supports this simplest form of concurrency. A Java programmer can simply write two or more programs, and then start them. Of course, since we re talking about Java, these programs have to be contained in some class we ll look at the classes (and interfaces) needed for this, and the support that Java provides for managing the complexities that arise from running several programs at the same time.
16 Concurrency in Java Concurrency in Java is programmed using threads. The notion of a thread of computation is captured in Java by the Thread class. In Java, all programs run in an instance of the Thread class. (main() methods run in a special thread called the main thread. Remember the error messages: Exception in thread "main"... ) terminal output
17 Concurrency in Java Concurrency in Java is programmed using threads. The notion of a thread of computation is captured in Java by the Thread class. In Java, all programs run in an instance of the Thread class. (main() methods run in a special thread called the main thread. Remember the error messages: Exception in thread "main"... ) terminal output
18 How to Write Concurrent Programs? You have to write the programs. A program is just a sequence of instructions (assignments, conditionals, loops, method-calls, etc.)... which is exactly what you can place in a void method in java. So writing a program is the same as writing a void method.
19 How to Write Concurrent Programs? You have to write the programs. A program is just a sequence of instructions (assignments, conditionals, loops, method-calls, etc.)... which is exactly what you can place in a void method in java. So writing a program is the same as writing a void method.
20 How to Write Concurrent Programs? You have to write the programs. A program is just a sequence of instructions (assignments, conditionals, loops, method-calls, etc.)... which is exactly what you can place in a void method in java. So writing a program is the same as writing a void method.
21 How to Write Concurrent Programs? You have to write the programs. A program is just a sequence of instructions (assignments, conditionals, loops, method-calls, etc.)... which is exactly what you can place in a void method in java. So writing a program is the same as writing a void method.
22 How to Write Concurrent Programs? You have to write the programs. A program is just a sequence of instructions (assignments, conditionals, loops, method-calls, etc.)... which is exactly what you can place in a void method in java. So writing a program is the same as writing a void method.
23 Interface java.lang.runnable An interface is a good way of specifying, in Java, a void method. This is exactly what is done by: public interface Runnable { public void run(); java.lang.runnable
24 Multithreading So you can write a program that you want to run concurrently with other programs by implementing interface Runnable. There is more to multithreading than just writing a program; the Java interpreter has to maintain a list of programs, and run them concurrently using time-slicing. The programmer gets the interpreter to do this with their program by: implementing interface Runnable with the program they want to run; creating a Thread (thread of computation) with that program; starting that Thread. You already know how to implement interfaces.
25 Multithreading So you can write a program that you want to run concurrently with other programs by implementing interface Runnable. There is more to multithreading than just writing a program; the Java interpreter has to maintain a list of programs, and run them concurrently using time-slicing. The programmer gets the interpreter to do this with their program by: implementing interface Runnable with the program they want to run; creating a Thread (thread of computation) with that program; starting that Thread. You already know how to implement interfaces.
26 Creating a Thread Class Thread has a constructor that takes a Runnable as a parameter. public Thread(Runnable r) {... in class Thread I.e., the actual parameter can be any instance of any class that implements Runnable. The code in the run method in that class is the code that will be run in the thread of computation.
27 Creating a Thread Class Thread has a constructor that takes a Runnable as a parameter. public Thread(Runnable r) {... in class Thread I.e., the actual parameter can be any instance of any class that implements Runnable. The code in the run method in that class is the code that will be run in the thread of computation.
28 Starting a Thread Class Thread has a method that will start a thread of computation. public void start() {... in class Thread This will tell the Java interpreter to start running the run method in that Thread, concurrently with any other Threads that have been started in this way. N.B. We don t call the run method directly: calling start() will register the thread of computation as a candidate for timeslicing; when the Java interpreter chooses that thread to actually run, it will execute the code in the run() method.
29 Starting a Thread Class Thread has a method that will start a thread of computation. public void start() {... in class Thread This will tell the Java interpreter to start running the run method in that Thread, concurrently with any other Threads that have been started in this way. N.B. We don t call the run method directly: calling start() will register the thread of computation as a candidate for timeslicing; when the Java interpreter chooses that thread to actually run, it will execute the code in the run() method.
30 Starting a Thread Class Thread has a method that will start a thread of computation. public void start() {... in class Thread This will tell the Java interpreter to start running the run method in that Thread, concurrently with any other Threads that have been started in this way. N.B. We don t call the run method directly: calling start() will register the thread of computation as a candidate for timeslicing; when the Java interpreter chooses that thread to actually run, it will execute the code in the run() method.
31 Example We will write a program that prints out the numbers from 0 to 40 to standard output. We will then run two of these programs as separate threads. The output will show the effect of time-slicing.
32 Implementing Runnable class NumberPrinter public class NumberPrinter implements Runnable { private String name; public NumberPrinter(String s) { name = s;
33 Implementing Runnable class NumberPrinter, contd. public void run() { for (int i=0; i < 40; i++) { System.out.println(name + ": " + i);
34 Starting Threads Our program will create two instances of NumberPrinter, and then start them running concurrently. We ll create two instances of class NumberPrinter, with different names ; then we ll create two threads with those two NumberPrinters; then we ll call the start() methods of those two Thread instances. (We won t call the NumberPrinter#run() methods directly; the Java interpreter will do that for us when we call the start() methods.)
35 The main() method in class NumberPrinter public static void main(string[] args) { NumberPrinter np1 = new NumberPrinter("John"); NumberPrinter np2 = new NumberPrinter("Jane"); Thread t1 = new Thread(np1); Thread t2 = new Thread(np2); t1.start(); t2.start();
36 The Output John: 1 John: 2 John: 3... John: 39 Jane: 1 Jane: 2... Jane: 39 terminal output
37 Inside the Java Interpreter The Java interpreter keeps a list of ready threads. These are: threads that have been started, have not yet finished, and are waiting to be chosen to run The Java interpreter chooses one thread from the ready pool, and executes it for some period of time (called a quantum ) then stops it, chooses another, etc., etc., until all threads have finished.
38 Run, John. Our example starts with only the main thread running. In that thread, two threads are created (t1 and t2). One of these is started (t1.start()). Now there are two ready threads: main and t1. Either main will continue to run (and start t2), or main will be stopped and t1 will run.
39 See John run. If (or when) main is allowed to continue, it will start t2, and there will be two ready threads: t1 and t2. The main thread has finished, and is no longer in the ready-pool. We say the thread is dead. There is no reason why t1 should be chosen before t2: this depends solely on how multi-threading is implemented in the Java interpreter. It so happens in this case that t1 is started, and allowed to finish, before t2 is chosen to run.
40 Experimenting By making the threads take longer to complete, different behaviours can be observed. On this machine, if the threads print out the numbers between 0 and 2000, then time-slicing can be seen in action:... John: 1004 John: 1005 Jane: 0 John: 1006 Jane: 1... terminal output
41 Leaving the Ready-Pool The choice of which thread from the ready-pool to run is made by the interpreter. However, the programmer does have some influence. A thread can pause by calling the Thread.sleep() method. It will stop running, and be put in a blocked pool for the specified number of milliseconds.
42 Trying to Sleep We introduce a call of sleep() to the run method in class NumberPrinter public void run() { for (int i=0; i < 40; i++) { System.out.println(name + ": try { Thread.sleep(10); changing class NumberPrinter catch(interruptedexception e) { " + i);
43 The Output John: 0 Jane: 0 John: 1 Jane: 1 John: 2 Jane: 2... terminal output
44 Let Sleeping Threads Lie When a thread calls the sleep(long) method, two things happen: 1 execution of that thread ceases for the specified number of milliseconds (the long parameter); 2 that thread is put into the blocked pool for the specified number of milliseconds; another thread will be chosen from the ready-pool to run; once the specified number of milliseconds have elapsed, the blocked thread will be put back into the ready-pool.
45 Getting Back in the Running Once it is moved back from the blocked pool to the ready-pool, the thread that called sleep() may be one among many in the ready-pool. There is no guarantee that that thread will recommence running after precisely the specified number of milliseconds. (In fact, it s unlikely.) The sleep() method is a way of letting other threads have their chance at running, and making sure that one thread doesn t monopolize the CPU.
46 Using Concurrency: Example 2 A common application of concurrency is in servers. Servers accept connections from remote clients; typically they receive some request from the client, and respond in some (application-dependent) way. Handling a request from a client may take some time, and while the server is busy processing and responding to the request, it is often desirable to allow other remote clients to connect to the server. I.e., it is often desirable to handle requests from several remote clients concurrently. Let s revisit the EchoServer example from Lecture 21.
47 Using Concurrency: Example 2 A common application of concurrency is in servers. Servers accept connections from remote clients; typically they receive some request from the client, and respond in some (application-dependent) way. Handling a request from a client may take some time, and while the server is busy processing and responding to the request, it is often desirable to allow other remote clients to connect to the server. I.e., it is often desirable to handle requests from several remote clients concurrently. Let s revisit the EchoServer example from Lecture 21.
48 Using Runnable Summary of using Threads: 1 declare a class that implements Runnable (i.e., gives a concrete run() method); 2 create an instance of that class; 3 create an instance of Thread using the Thread(Runnable) constructor; 4 start the thread. We ll do this for the session-handling part of EchoServer,
49 Handling Multiple Sessions We could allow sessions to be handled concurrently by using threads: class ThreadedEchoServer { public static void main(string[] args) { // used to handle sessions Thread t; try { ServerSocket ss = new ServerSocket(8189);
50 Handling Multiple Sessions while (true) { class ThreadedEchoServer, contd. Socket incoming = ss.accept( ); t = new Thread(new EchoHandler(incoming)); t.start(); catch (Exception e) { System.err.println(e.getMessage());
51 Handling Multiple Sessions Our session-handling code goes into a class that implements Runnable: class ThreadedEchoHandler implements Runnable { Socket client; ThreadedEchoHandler(Socket s) { client = s;
52 ... so it must have a run() method: Handling Multiple Sessions public void run() { try { BufferedReader in =...; PrintWriter out =...; out.println("hello!..."); out.flush(); // as before... class EchoHandler, contd. NB when the user ends the session, the thread dies.
53 Again, we can connect to the server using telnet. Using telnet Because the server creates threads to handle each session, we can have multiple telnet sessions all connected to the server at the same time.
54 Adding State to the Server The ThreadedEchoServer is very simple. Most servers either control access to some data (e.g., web servers), or allow remote clients to add data (e.g., message board servers). We can add some data to the ThreadedEchoServer by keeping count of how many clients connect to the server, how many clients are currently connected, and how many I/O exceptions have been thrown. We ll develop a class to keep count of connections and exceptions, then the server will: create an instance of this class, and share this instance with all the session-handling threads, so that it can keep track of all connections and exceptions
55 class ConnectionCounter { Keeping Count private int connections = 0; private int currentconnections = 0; private int exceptions = 0; public int getconnections() { return connections; class ConnectionCounter public int getcurrentconnections() { return currentconnections; public int getexceptions() { return exceptions;
56 class ConnectionCounter { Keeping Count private int connections = 0; private int currentconnections = 0; private int exceptions = 0; public int getconnections() { return connections; class ConnectionCounter public int getcurrentconnections() { return currentconnections; public int getexceptions() { return exceptions;
57 class ConnectionCounter { Keeping Count private int connections = 0; private int currentconnections = 0; private int exceptions = 0; public int getconnections() { return connections; class ConnectionCounter public int getcurrentconnections() { return currentconnections; public int getexceptions() { return exceptions;
58 class ConnectionCounter { Keeping Count private int connections = 0; private int currentconnections = 0; private int exceptions = 0; public int getconnections() { return connections; class ConnectionCounter public int getcurrentconnections() { return currentconnections; public int getexceptions() { return exceptions;
59 Keeping Count public void addconnection() { connections++; currentconnections++; public void endsession() { currentconnections--; public void countexception() { exceptions++; class ConnectionCounter, contd.
60 Passing References The server will create a ConnectionCounter instance, but it s the session-handling threads that need access to the counter. How do we let each thread use the counter? in the server class public static void main(string[] args) { ConnectionCounter stato = new ConnectionCounter(); while (true) { Socket incomming = ss.accept(); new Thread( new StatHandler(incoming, stato) ).start();...
61 Passing References The server will create a ConnectionCounter instance, but it s the session-handling threads that need access to the counter. How do we let each thread use the counter? in the server class public static void main(string[] args) { ConnectionCounter stato = new ConnectionCounter(); while (true) { Socket incomming = ss.accept(); new Thread( new StatHandler(incoming, stato) ).start();...
62 Passing References The server will create a ConnectionCounter instance, but it s the session-handling threads that need access to the counter. How do we let each thread use the counter? in the server class public static void main(string[] args) { ConnectionCounter stato = new ConnectionCounter(); while (true) { Socket incomming = ss.accept(); new Thread( new StatHandler(incoming, stato) ).start();...
63 Passing References The server will create a ConnectionCounter instance, but it s the session-handling threads that need access to the counter. How do we let each thread use the counter? in the server class public static void main(string[] args) { ConnectionCounter stato = new ConnectionCounter(); while (true) { Socket incomming = ss.accept(); new Thread( new StatHandler(incoming, stato) ).start();...
64 Storing Passed References the session-handler class class StatHandler implements Runnable { private Socket client; private ConnectionCounter counter; StatHandler(Socket s, ConnectionCounter cc) { client = s; counter = cc; Store the passed reference to the Socket Store the passed reference to the ConnectionCounter
65 Storing Passed References the session-handler class class StatHandler implements Runnable { private Socket client; private ConnectionCounter counter; StatHandler(Socket s, ConnectionCounter cc) { client = s; counter = cc; Store the passed reference to the Socket Store the passed reference to the ConnectionCounter
66 Storing Passed References the session-handler class class StatHandler implements Runnable { private Socket client; private ConnectionCounter counter; StatHandler(Socket s, ConnectionCounter cc) { client = s; counter = cc; Store the passed reference to the Socket Store the passed reference to the ConnectionCounter
67 Being Principled If an instance of one class needs to use an instance of another class, use the constructor to pass the required instance, and store it in a field. Principle
68 Using Passed/Stored References public void run() { counter.addconnection();... try { // set up I/O streams... session-handler class, contd
69 Using Passed/Stored References session-handler class, contd. while (true) { line = in.readline();... if (line.equals("0s")) { out.println("connections: " + counter.getconnections()); out.println("currently : " + counter.getcurrentconnections()); out.println("exceptions : " + counter.getexceptions());
70 Using Passed/Stored References session-handler class, contd. catchioexception ioe) { counter.countexception(); finally { // shut down streams and socket... counter.endsession();
71 That s All, Folks! Summary Threads interface Runnable multi-threaded Servers Next: loose threads
COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming
COMP 213 Advanced Object-oriented Programming Lecture 20 Network Programming Network Programming A network consists of several computers connected so that data can be sent from one to another. Network
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 informationLe L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading
Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that
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 informationObject Oriented Programming. Week 10 Part 1 Threads
Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that
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 informationCMSC 433 Programming Language Technologies and Paradigms. Concurrency
CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.
More informationTopic 10: Network Programming
Topic 10: Network Programming Client-Server Model Host and Port Socket Implementing Client Implementing Server Implementing Server for Multiple Clients Client-Server Model Clients Request a server to provide
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 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 informationCOURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread
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 informationDeadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.
Deadlock A set of processes is deadlocked if each process in the set is waiting for an event that can be caused by another process in the set. The events that we are mainly concerned with are resource
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2017 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output
COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output
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 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 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 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 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 informationCS360 Lecture 12 Multithreading
CS360 Lecture 12 Multithreading Thursday, March 11, 2004 Reading Multithreading: Chapter 16 Thread States At any time, a thread can be in one of several thread states: - Born: this is the time when the
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Winter 2015 Reading: Chapter 2, Relevant Links Some Material in these slides from J.F Kurose and K.W. Ross All material copyright
More informationProgramming Methods Dr Robert Harle
Programming Methods Dr Robert Harle IA NST CS and CST Lent 2008/09 Handout 4 Our Motivating Example We re going to make the world s simplest web server It s not going to challenge apache etc But it will
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 informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2018 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
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 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 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 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 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 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 informationThreads & Timers. CSE260, Computer Science B: Honors Stony Brook University
Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one
More informationICOM 4015-Advanced Programming. Spring Instructor: Dr. Amir H. Chinaei. TAs: Hector Franqui, Jose Garcia, and Antonio Tapia. Reference: Big Java
ICOM 4015-Advanced Programming Spring 2014 Instructor: Dr. Amir H. Chinaei TAs: Hector Franqui, Jose Garcia, and Antonio Tapia Reference: Big Java By Hortsmann, Ed 4 Lab 7 Continuation of HTTP and Introduction
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 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 informationG52CON: Concepts of Concurrency
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads
More informationCPS221 Lecture: Threads
Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process
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 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 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 Assistant Professor DCS Operating System Concepts
Threads Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS Lahore Pakistan Operating System Concepts Definitions Threads In the previous discussion, a process
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 informationLecture 7: Process & Thread Introduction
COMP 150-CCP Concurrent Programming Lecture 7: Process & Thread Introduction Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 7, 2008 Operating System Concepts Definition of a
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 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 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 informationBSc ( Hons) Computer Science with Network Security. Examinations for / Semester 2
BSc ( Hons) Computer Science with Network Security Cohort: BCNS/16B/FT Examinations for 2017 2018 / Semester 2 Resit Examinations for BCNS/15B/FT & BCNS/16A/FT MODULE: NETWORK PROGRAMMING MODULE CODE:
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 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 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 informationReintroduction to Concurrency
Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking
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 informationPrevious lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL
Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 What is a thread Why use multiple threads Issues and problems involved Java threads Natasha Alechina School of Computer
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 informationDistributed Systems Recitation 2. Tamim Jabban
15-440 Distributed Systems Recitation 2 Tamim Jabban Agenda Communication via Sockets in Java (this enables you to complete PS1 and start P1 (goes out today!)) Multi-threading in Java Coding a full Client-Server
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 informationOverview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions
CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to
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 informationMultithreading in Java Part 2 Thread - States JAVA9S.com
Multithreading in Java Part 2 Thread - States By, Srinivas Reddy.S When start() method is invoked on thread It is said to be in Runnable state. But it is not actually executing the run method. It is ready
More informationJAVA - MULTITHREADING
JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program
More informationCERTIFICATION OBJECTIVES
9 Threads CERTIFICATION OBJECTIVES Defining, Instantiating, and Starting Threads Preventing Thread Execution Synchronizing Code Thread Interaction Q&A Two-Minute Drill Self Test 2 Chapter 9: Threads CERTIFICATION
More informationThread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections
Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent
More informationMultithreaded Programming
Multithreaded Programming http://www.motifake.com/multi-tasking-baby-dishes-bath-wash-demotivational-posters-118837.html Traditional Multi-tasking - One CPU - Many users, each wishing to use a computer
More informationMultithread Computing
Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread
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 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 informationAdvanced Java Programming. Networking
Advanced Java Programming Networking Eran Werner and Ohad Barzilay Tel-Aviv University Advanced Java Programming, Spring 2006 1 Overview of networking Advanced Java Programming, Spring 2006 2 TCP/IP protocol
More informationCST242 Concurrency Page 1
CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor
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 informationUnit III Rupali Sherekar 2017
Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception
More informationCIS233J Java Programming II. Threads
CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential
More informationBy: Abhishek Khare (SVIM - INDORE M.P)
By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying
More informationMultithreaded Programming
Multithreaded Programming http://www.motifake.com/multi-tasking-baby-dishes-bath-wash-demotivational-posters-118837.html http://thechive.com/2014/01/15/champions-of-multitasking-35-photos/ www.funscrape.com/meme/62260
More informationSUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams
SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi
More informationDining philosophers (cont)
Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs this week for a demo time Office hour today will be cut short (11:30) Another faculty
More informationCOMP346 Winter Tutorial 4 Synchronization Semaphores
COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated
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 informationNetworking Code CSCI 201 Principles of Software Development
Networking Code CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Server Networking Client Networking Program Outline USC CSCI 201L Server Software A server application
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 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 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 informationCOMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION
COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.
More information04-Java Multithreading
04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org
More informationJava using LEGO Mindstorms and LeJOS. University of Idaho
Java using LEGO Mindstorms and LeJOS University of Idaho 2 Contents 1 Introduction 1 1.1 Setting up Java and Eclipse................................ 1 1.2 Setting up the Lego Brick to work with LeJOS.....................
More informationSocket programming. Complement for the programming assignment INFO-0010
Socket programming Complement for the programming assignment INFO-0010 Outline Socket definition Briefing on the Socket API A simple example in Java Multi-threading and Synchronization Example : HTTP protocol
More informationWhat is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal
Java Threads What is a Thread? Individual and separate unit of execution that is part of a process multiple threads can work together to accomplish a common goal Video Game example one thread for graphics
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 informationPerformance Throughput Utilization of system resources
Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency
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 informationLecture 5: RMI etc. Servant. Java Remote Method Invocation Invocation Semantics Distributed Events CDK: Chapter 5 TVS: Section 8.3
Lecture 5: RMI etc. Java Remote Method Invocation Invocation Semantics Distributed Events CDK: Chapter 5 TVS: Section 8.3 CDK Figure 5.7 The role of proxy and skeleton in remote method invocation client
More informationIntroduction to Sockets
Introduction to Sockets Sockets in Java 07/02/2012 EPL 602 1 Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API o introduced in BSD4.1 UNIX,
More informationJava Programming Language Advance Feature
Java Programming Language Advance Feature Peter.Cheng founder_chen@yahoo.com.cn http://www.huihoo.com 2004-04 Huihoo - Enterprise Open Source http://www.huihoo.com 1 Course Goal The main goal of this course
More informationCS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11
CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 11 EXCEPTION HANDLING Many higher-level languages provide exception handling Concept: One part of the program knows how to detect a problem,
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 informationMULTI-THREADING
MULTI-THREADING KEY OBJECTIVES After completing this chapter readers will be able to understand what multi-threaded programs are learn how to write multi-threaded programs learn how to interrupt, suspend
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 informationSoftware Practice 1 - Socket
Software Practice 1 - Socket Terms of socket programming Socket Implementation (TCP, UDP) Socket with multithread Serialization Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin
More informationCOP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads. Zhi Wang Florida State University
COP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads Zhi Wang Florida State University Contents Thread overview Multithreading models Thread libraries Threading issues Operating
More informationpackage p1; public class Derivation extends Protection { public Derivation() { System.out.println("Derived class constructor");
PROGRAM:1 WAP to implement the packages //package 1: package p1; public class Protection int n=1; public int n_pub=2; private int n_pri=3; protected int n_pro=4; public Protection () System.out.println("Base
More information