Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Similar documents
CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Multithreaded Programming

Definition: A thread is a single sequential flow of control within a program.

7. MULTITHREDED PROGRAMMING

Threads Chate Patanothai

Threads in Java (Deitel & Deitel)

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Introduction to Java Threads

CS 556 Distributed Systems

Multi-threading in Java. Jeff HUANG

CMSC 132: Object-Oriented Programming II. Threads in Java

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Advanced Concepts of Programming

Java Threads. Introduction to Java Threads

Animation Part 2: MoveableShape interface & Multithreading

Contents. 6-1 Copyright (c) N. Afshartous

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Object Oriented Programming (II-Year CSE II-Sem-R09)

CSCD 330 Network Programming

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

CSCD 330 Network Programming

CSCD 330 Network Programming

Module - 4 Multi-Threaded Programming

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary

CS 351 Design of Large Programs Threads and Concurrency

Multithreading Pearson Education, Inc. All rights reserved.

Concurrent Programming

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

TCP connections. Fundamentals of Internet Connections Objectives. Connect to an Echo port. java.net.socket

User Space Multithreading. Computer Science, University of Warwick

Synchronization synchronization.

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs.

Performance Throughput Utilization of system resources

CS180 Review. Recitation Week 15

Multithreaded Programming

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Java s Implementation of Concurrency, and how to use it in our applications.

Part IV Other Systems: I Java Threads

Unit - IV Multi-Threading

BSc ( Hons) Computer Science with Network Security. Examinations for / Semester 2

Java Networking (sockets)

Java Threads. COMP 585 Noteset #2 1

URL Kullanımı Get URL

Connecting to a Server Implementing Servers Making URL Connections Advanced Socket Programming

Multithreading in Java Part 2 Thread - States JAVA9S.com

Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Concurrency and Java Programming

Introduction to Sockets

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Threads. What Is a Thread? Customizing a Thread's run Method. Understanding Threads. Subclassing Thread and Overriding run. Thread Objects.

Chapter 32 Multithreading and Parallel Programming

CS360 Lecture 12 Multithreading

Threads and Parallelism in Java

Advanced Programming Concurrency

THREADS. Laboratório - Java

Software Practice 1 - Multithreading

Threads and Java Memory Model

Multithreading using Java. Dr. Ferdin Joe John Joseph

pre-emptive non pre-emptive

Java Support for developing TCP Network Based Programs

Topic 10: Network Programming

What is a thread anyway?

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

04-Java Multithreading

Multithread Computing

COMP 322: Fundamentals of Parallel Programming

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Networking Code CSCI 201 Principles of Software Development

Object Oriented Programming. Week 10 Part 1 Threads

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Java Programming Language Advance Feature

Chapter 19 Multithreading

public class Shared0 { private static int x = 0, y = 0;

Java for Interfaces and Networks

Java Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Le 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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

Synchronisation in Java - Java Monitor

JAVA - NETWORKING (SOCKET PROGRAMMING)

Java Threads and intrinsic locks

M257 Past Paper Oct 2007 Attempted Solution

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Internet Technology 2/7/2013

Question Points Score Total 100

Parallel Programming Practice

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Concurrent, Real-Time and Distributed Programming in Java

Java for Interfaces and Networks (DT3029)

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Parallel Programming Practice

Programming Java. Multithreaded Programming

31 Network Programming

Concurrent Computing CSCI 201 Principles of Software Development

Chapter 3: A Larger Example: SocketChat

Transcription:

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) is an address of a resource on the Internet (protocolid:resourcename). Socket-based communication between programs. A socket is one end of a two-way communication link between two programs running on the network. Communication based on datagrams. The delivery of datagrams is not guaranteed nor is the order in which they are delivered.

Reading from URL Intent - open URL http://www.yahoo.com, get an input stream on the connection, and read from the input stream. import java.io.*; import java.*; public class URLExample { public static void main(string[] args) { try { URL urlkozusznik = new URL("http://www.kozusznik.cz"); URLConnection conn = urlkozusznik.openconnection(); try ( BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while (null!= (line = r.readline())) { System.out.println(line); catch (IOException e) { e.printstacktrace();

The Socket Model The server establishes a port number and waits. When the client requests a connection, the server opens the socket connection with the accept() method. The client establishes a connection with host on a given port #. Both client ans server communicate using InputStream and OutputStream. Server ServerSocket(port) accept() OutputStream InputStream close() Client Socket(host, port) // attempt to connect OutputStream InputStream close()

Example: Simple Server Intent - wait for client and send it a message when connected. public class SimpleServer { ServerSocket server; String message = "Hello from server!"; public void run() { try { server = new ServerSocket(5432, 5); listen(); catch (Exception e) { // protected void listen() { try { while(true) { Socket client = server.accept(); ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream()); out.writeobject(message); client.close(); catch (Exception e) { //

Example: Simple Client Intent - connect to the server and get a message. public class SimpleClient { public void run(string host) { try { Socket server = new Socket(host,5432); ObjectInputStream input = new ObjectInputStream(server.getInputStream()); System.out.println(input.readObject()); server.close(); catch (Exception e) { System.out.println("Error while getting message!");

Example: Simple Client Intent - connect to the server and get a message. public class SimpleClient { public void run(string host) { try(socket server = new Socket(host,5432)) { ObjectInputStream input = new ObjectInputStream(server.getInputStream()); System.out.println(input.readObject()); catch (Exception e) { System.out.println("Error while getting message!");

Client/Server Application public class ServerTest { public static void main(string[] args) { new SimpleServer().run(); public class ClientTest { public static void main(string[] args) { new SimpleClient().run(args[0]);

Thread of execution is the smallest sequence of programmed instructions that can be managed independently by an operating system scheduler Multiple threads can exists in one process (running programs) and they share resources (memory)

Threads Represented by class Thread Its method run() serves as a main routine for the thread. A thread can be in state runnable, not runnable (sleep(), wait() or blocking I/O) and dead (completion of the run() method). A thread can have a priority from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10).

java.lang.thread a multithreading friend Define subclass (class MyThread1 e.g.) of the class Thread Override method run this code will be executed in new thread Create new instance of your class (MyThread1) and call the method start thread end after leaving method run

Thread execution in an action Intent - create two threads that each print out their own text. public class PrintThread extends Thread { String name; int delay; public PrintThread(String name, int delay) { this.name = name; this.delay = delay; public void run() { try { Thread.sleep(delay); catch (InterruptedException e) { System.out.println( Hello from +name); t1 = new PrintThread( #1,(int) (Math.random()*2000)); t2 = new PrintThread( #2,(int) (Math.random()*2000)); t1.start(); t2.start();

Interface Runnable Interface Runnable declares a run() method. t1 = new Print ( #1,(int) (Math.random()*2000)); t2 = new Print ( #2,(int) (Math.random()*2000)); new Thread(t1).start(); // start() calls run() new Thread(t2).start(); public class Print implements Runnable { String name; int delay; public Print (String name, int delay) { this.name = name; this.delay = delay; public void run() { try { Thread.sleep(delay); catch (InterruptedException e) { System.out.println( Hello from +name);

Method join public class ProducerConsumerTest { public static void main(string[] args) { Pool pool = new Pool(); Producer p = new Producer(pool); Consumer c = new Consumer(pool); p.start(); c.start(); p.join(); c.join(); System.out.println( Threads ended!! );

Method interrupt Method of class Thread signalization of interruption In thread is inspected by method isinterrupted whether interruption was signaled.

Synchronization Since Java is a multithreaded system, care must be taken to prevent multiple threads from modifying objects simultaneously. Section of code that must not be executed simultaneously are known as critical section. Statement synchronized: synchronized (expression) statement - expression must resolve to an object or array - statement is the code of critical section. The synchronized statement attemps to acquire an exclusive lock for the object or array and it does not execute the critical section code until it can obtain this lock. Method modifier synchronized indicates that entire method is critical section code. For a synchronized instance method, Java obtains an exclusive lock on the class instance. For a synchronized class method, Java obtains an exclusive lock on the class.

Monitor A monitor is associated with a specific object (or array) and functions as a lock on that object. When a thread holds the monitor for some object, other threads are locked out and cannot inspect or modify this object. The Java runtime system allows a thread to re-acquire a monitor that it already holds because Java monitors are reentrant. Reentrant monitors are important because they eliminate the possibility of a single thread deadlocking itself on a monitor that it already holds. class Reentrant { public synchronized void a() { b(); System.out.println("here I am, in a()"); public synchronized void b() { System.out.println("here I am, in b()");

Multiple-Thread Communication Method wait() of the Object class makes a thread wait until some condition occurs. Method notify() of the Object class tells a waiting thread that a condition occured.

Example: Producer/Consumer Intent - the Producer generates an integer between 0 and 9, stores it in a Pool object, and prints the generated number. To make the synchronization problem more interesting, the Producer sleeps for a random amount of time between 0 and 1000 milliseconds before repeating the number generating cycle. The Consumer consumes all integers from the Pool (the exact same object into which the Producer put the integers in the first place) as quickly as they become available.

Producer public class Producer extends Thread { private Pool pool; public Producer(Pool pool) { this.pool = pool; public void run() { for (int i = 0; i < 10; i++) { pool.put(i); // Wait until the previous value is consumed System.out.println("Producer put: " + i); try { sleep((int)(math.random() * 1000)); catch (InterruptedException e) {

Consumer public class Consumer extends Thread { private Pool pool; public Consumer(Pool pool) { this.pool = pool; public void run() { int value; for (int i = 0; i < 10; i++) { value = pool.get(); // Wait until the value is produced System.out.println("Consumer got: " + value);

public class Pool { private int contents; private boolean isfull = false; public synchronized int get() { While (! isfull) { try { wait(); catch (InterruptedException e) { int value = contents; isfull = false; notifyall(); return value; Shared Pool public synchronized void put(int i) { while (isfull) { try { wait(); catch (InterruptedException e) { contents = i; isfull = true; notifyall();

Producer/Consumer Test public class ProducerConsumerTest { public static void main(string[] args) { Pool pool = new Pool(); Producer p = new Producer(pool); Consumer c = new Consumer(pool); p.start(); c.start();