Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.

Slides:



Advertisements
Similar presentations
CS4273: Distributed System Technologies and Programming I Lecture 4: Java Threads and Multithread Programming.
Advertisements

Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Object-Oriented Software Engineering Concurrent Programming.
CSE S. Tanimoto Java Threads 1 Java Threads (Outline) Motivation The class Thread Example program: ThreadRace The Runnable interface Example: Clock.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
28-Jun-15 Producer-Consumer An example of using Threads.
Lesson 9 Intro to Java Threads. What are threads?  Like several concurrent subprograms running within the same address space.  Within a program, individual.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
1 Handout 10 MULTI-THREADING BY GEORGE KOUTSOGIANNAKIS THIS DOCUMENT CAN NOT BE REPRODUCED OR DISTRIBUTED WITHOUT TH E WRITTEN PERMISSION OF THE AUTHOR.
„Threads”. Threads Threads - basics A thread is a single sequential flow of control within a program. A thread itself is not a program; it cannot run.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Multithreading.
תכנות מקבילי - I יישום ב- Java. References קורס "תכנות מקבילי ומבוזר", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
1 Java Threads Instructor: Mainak Chaudhuri
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads CSCE 190 – Java Instructor: Joel Gompert Wed, Aug 3, 2004.
Java Threads and higher level constructs for doing concurrent programming.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Chapter 6 (6.7 & 6.9 only) - Threads & Mutex Threads –A Thread is a basic unit of CPU utilization consisting of a program counter, register set and stack.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Threading and Concurrency COM379T John Murray –
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Java 3: Odds & Ends Advanced Programming Techniques.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multi-Threading in Java
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Multithreading and Garbage Collection Session 16.
THREAD MODEL.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
Multithreading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Multithreading.
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
Java Threads (Outline)
Java Threads (Outline)
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Representation and Management of Data on the Internet
Gentle Introduction to Threads
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application. The server should be capable of handling multiple appointment books and clients. Appointment times should be stored in a file.

Let's use student advising as an example. Each faculty member has a set of times that he is available for advising. This information is stored in a file that is identified by faculty member. Students start an application that will access the appointment book server. They identify their advisor, and a list of possible appointment times is given. The student enters their name for the given time, and this appointment is stored in a file.

Use Case A use case is a theme for interacting with the system Various external entities interact with the system Use system in different ways Use case drives discovery of classes and associations Use cases can translate into methods

Threads A thread is a single sequential flow of control within a program A thread is not a program but runs within a program. Lightweight process: Runs in context of full-blown program and uses its resources Execution Context: Carves out its own resources within the program

Run Method Gives Thread something to do Implements Thread’s running behavior Thread class implements a default thread that does nothing Its run() method is empty Override to implement a runnable object’s behavior

Two Ways Thread class in java.lang Subclass Thread and implement run method Implement the Runnable interface Both require that the run method (what the thread does at runtime) be implemented by your class.

public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); //sets name of thread } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); }

public class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); }

import java.awt.Graphics; import java.util.*; import java.text.DateFormat; import java.applet.Applet; public class Clock extends Applet implements Runnable { private Thread clockThread = null; public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); }

public void run() { Thread myThread = Thread.currentThread() while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){ // the VM doesn't want us to sleep anymore, // so get back to work }

public void paint(Graphics g) { // get the time and convert it to a date Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); // format it and display it DateFormat dateFormatter = DateFormat.getTimeInstance(); g.drawString(dateFormatter.format(date), 5, 10); } // overrides Applet's stop method, not Thread's public void stop() { clockThread = null; }

Life Cylce of a Thread

Life Cycle Create: New Thread state is empty thread object. Gets run method from target “ this ”. start () creates system resources for the thread, schedules thread, and calls run (). Not Runnable if sleep () (time elapses), wait () (notification from another object), or blocked on I/O (I/O completes).

Stopping run method that terminates gracefully. No stop method (as in Applet) Condition for termination. Dead condition

Priority CPU Scheduling of the thread. Based on fixed priority scheduling setPriority (), inherits priority, priority is an integer from MIN_PRIORITY to MAX_PRIORITY (higher, higher priority) Round-robin for equal priority. yield () method or Time slicing (system). Preemption by higher priority threads.

public class RaceTest { private final static int NUMRUNNERS = 2; public static void main(String[] args) { SelfishRunner[] runners = new SelfishRunner[NUMRUNNERS]; for (int i = 0; i < NUMRUNNERS; i++) { runners[i] = new SelfishRunner(i); runners[i].setPriority(2); } for (int i = 0; i < NUMRUNNERS; i++) runners[i].start(); }

Synchronizing Threads Shared Data Critical Sections: same object accessed by separate, concurrent threads. synchronized keyword Java associates a lock with every object within synchronized code

/** Jun 1997 Cay Horstmann */ class SynchBankTest { public static void main(String[] args) { Bank b = new Bank();/*object shared by all transaction sources*/ int i; for (i = 1; i <= Bank.NACCOUNTS; i++) new TransactionSource(b, i).start(); } This is application from command line. Set up a Bank and start transaction threads on each account. Simulate 10 bank accounts. Randomly generate transactions that move money between accounts. There is a thread for each account. Each transaction moves a random amount of money.

class Bank { public Bank() { accounts = new long[NACCOUNTS]; int i; for (i = 0; i < NACCOUNTS; i++) accounts[i] = INITIAL_BALANCE; ntransacts = 0; test(); }/*Populate accounts with money*/ /*accounts corrupted if not synchronized*/ public synchronized void transfer(int from, int to, int amount) { while (accounts[from] < amount)/*current thread blocked, gives up lock*/ { try { wait(); } catch(InterruptedException e) {} }/*if not enough money, wait for more*/ accounts[from] -= amount; accounts[to] += amount; ntransacts++; if (ntransacts % 5000 == 0) test(); notifyAll(); /*let everybody check for enough money*/ }

public void test() /*how much in each account?*/ { int i; long sum = 0; for (i = 0; i < NACCOUNTS; i++) sum += accounts[i]; System.out.println("Transactions:" + ntransacts + " Sum: " + sum); } public static final int INITIAL_BALANCE = 10000; public static final int NACCOUNTS = 10; private long[] accounts; private int ntransacts; }

class TransactionSource extends Thread { public TransactionSource(Bank b, int i) { from = i - 1; bank = b; } public void run() { while (true) { int to = (int)(Bank.NACCOUNTS * Math.random()); if (to == from) to = (to + 1) % Bank.NACCOUNTS; int amount = (int)(Bank.INITIAL_BALANCE * Math.random()); bank.transfer(from, to, amount); try { sleep(1); } catch(InterruptedException e) {} } private Bank bank; private int from; }

Cubbyhole Example

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

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

Locking an Object Consumer should not access CubbyHole when Producer changing it, and Producer should not access it when Consumer getting value. Object locked until unlocked. Threads must have a way to communicate condition changes to each other

Note that the method declarations for both put and get contain the synchronized keyword. Hence, the system associates a unique lock with every instance of CubbyHole (including the one shared by the Producer and the Consumer). Whenever control enters a synchronized method, the thread that called the method locks the object whose method has been called. Other threads cannot call a synchronized method on the same object until the object is unlocked. So, when the Producer calls CubbyHole's put method, it locks the CubbyHole, thereby preventing the Consumer from calling the CubbyHole's get method: boolean available is true when the value has just been put but not yet gotten and is false when the value has been gotten but not yet put.

Thread Communication notify (), notifyAll (), wait () methods from Object get loops until Producer produces new value. wait relinquishes lock on CubbyHole by Consumer waits on notification from Producer

wait() : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. notify() : Wakes up a single thread that is waiting on this object's monitor. notifyAll() : Wakes up all threads that are waiting on this object's monitor.