Threads. Thread = independent flow of control e.g. a server needs to communicate with many customers => each customer is served by a separate thread.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
CSE S. Tanimoto Java Threads 1 Java Threads (Outline) Motivation The class Thread Example program: ThreadRace The Runnable interface Example: Clock.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Critical Reference An occurrence of a variable v is defined to be critical reference: a. if it is assigned to in one process and has an occurrence in another.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
1 Lecture 11(chap 14) Exception Handling & Thread Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 Web Based Programming Section 8 James King 12 August 2003.
Object Oriented Programming Lecture 5: Refactoring by Inheritance and Delegation - A simple Design Pattern for animation applets, A Generic Function Plotter.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Multi-Threading in Java
1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
More OOP. Extending other’s classes extend Java platform classes, e.g. class Applet public class MyApplet extends Applet { public void init() { } public.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Java Applets Getting Started. Import Files In order to run the applet properly, we have to import some files into our class. These files are: –import.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Chapter 13: Multithreading
Exceptions: When things go wrong
MIT AITI 2003 Lecture14 Exceptions
Multithreading in Java
Threads Chate Patanothai.
ATS Application Programming: Java Programming
Java Threads (Outline)
Java Threads (Outline)
Chapter 15 Multithreading
Java Programming COMP-417 Applet
Concurrent programming
Presentation transcript:

Threads

Thread = independent flow of control e.g. a server needs to communicate with many customers => each customer is served by a separate thread

Threads – toy example increments x increments y calls repaint MyApplet

Threads – toy example import java.applet.Applet; import java.awt.*; public class FirstApplet extends Applet { public int x,y; public void init() {.... } public void paint(Graphics g) { g.setColor(Color.white); g.setFont(new Font("SansSerif",Font.BOLD,32)); g.drawString("x="+x,10,40); g.drawString("y="+y,10,80); g.drawString("x-y="+(x-y),10,120); }

public void init() { setBackground(Color.black); new Thread(new Runnable () { public void run() { while (true) { x++; } }}).start(); new Thread(new Runnable () { public void run() { while (true) { y++; } }}).start(); new Thread(new Runnable () { public void run() { while (true) { try { Thread.currentThread().sleep(40); } catch (InterruptedException e) {}; repaint(); } }}).start(); } 1.create 2.start

Runnable interface run() - method Thread(Runnable r); a constructor of the Thread class

Anonymous classes new Thread(new Runnable () { public void run() { while (true) { y++; } }).start(); new ClassName() { { ? } ? } instance initializer local variables

Time slicing Thread 1 Thread 2 Thread 3 Thread 1 Thread 2 Thread 3 Thread 2 Thread 3 time

Threads - priorities new Thread(new Runnable () { public void run() { try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); } catch (IllegalArgumentException e) {} catch (SecurityException e) {} while (true) { x++; } }}).start(); MyApplet

Synchronization problems object Thread 1 Thread 2 Extremely difficult to debug...

Synchronization problems – toy example x,dx Thread 1 Thread 2 while (true) { x+=1000; dx=-1; for (i=0;i<1000;i++) x+=dx; } while (true) { x-=1000; dx=+1; for (i=0;i<1000;i++) x+=dx; } MyApplet

public void init() { new Thread(new Runnable () { public void run() { while (true) { x+=1000; dx=-1; for (i=0;i<1000;i++) x+=dx; } }}).start(); new Thread(new Runnable () { public void run() { while (true) { x-=1000; dx=+1; for (i=0;i<1000;i++) x+=dx; } }}).start();..... } Synchronization problems – toy example

synchronized blocks of code object Thread 1 Thread 2 Do not touch the object.

synchronized blocks of code public void init() { new Thread(new Runnable () { public void run() { while (true) { synchronized(lock) { x+=1000; dx=-1; for (i=0;i<1000;i++) x+=dx; } }}).start(); new Thread(new Runnable () { public void run() { while (true) { synchronized(lock) { x-=1000; dx=+1; for (i=0;i<1000;i++) x+=dx; } }}).start(); } MyApplet

synchronized blocks of code public void init() { new Thread(new Runnable () { public void run() { synchronized(lock) { while (true) { x+=1000; t1++; dx=-1; for (i=0;i<1000;i++) x+=dx; } }}).start(); new Thread(new Runnable () { public void run() { synchronized(lock) { while(true) { x-=1000; t2++; dx=+1; for (i=0;i<1000;i++) x+=dx; } }}).start(); } MyApplet

synchronized methods synchronized ? method(?) { ? } ? method(?) { synchronized(this) { ? }

stop() deprecated – can leave objects it is manipulating in inconsistent state pleaseStop() define your own

wait() and notify() class Pipe { LinkedList l=new LinkedList(); public synchronized void Push(Object o) { l.add(o); this.notify(); } public synchronized Object Pop() { while (l.size()==0) { try { this.wait(); } catch (InterruptedException e) { } } return l.remove(0); }

Sleeping threads try { Thread.currentThread().sleep(40); } catch (InterruptedException e) {};

Exceptions

method() some unexpected situation can occur throw an exception try { method(); } catch (TypeOfTheException e) { // deal with the exception }

Exceptions try { } catch (TypeOfTheException e) { } Code dealing with “normal” execution Code dealing with “exceptions”

Exceptions are objects class NoElectricityException extends Exception { NoElectricityException() { super(“No electricity!”); } NoElectricityException(String message) { super(message); } getMessage() method

Exceptions are objects Class Chef {... Food makeRoastBeef(Kitchen k) { if (!k.lightOn()) { k.turnLightOn(); if (!k.lightOn()) throw new NoElectricityException();... }... }

Exceptions are objects Food[] prepareDinner() { try { f=makeRoastBeef(k); } catch (NoElectricityException e) { ? }

Exceptions Throwable Exception Error RuntimeException checked unchecked

Exceptions examples InterruptedException RuntimeException ArithmeticException IndexOutOfBoundException ArrayIndexOutOfBoundException NullPointerException Error OutOfMemoryError

Throws Food makeRoastBeef(Kitchen k) throws NoElectricityException, NoMeatException,... {... } checked exceptions

try/catch/finally try { } catch (TypeOfTheException e){ } finally { }

try { System.out.println(“1”); if (x==0) throw(new MyException()); } catch (MyException e){ System.out.println(“3”); } finally { System.out.println(“2”); } EXERCISE: what will be the ouput for a) x=1 b) x=0

void Test(int x) throws YourException { try { System.out.println(“1”); if (x==0) throw(new MyException()); if (x==1) throw(new YourException()); if (x==2) return; System.out.println(“4”); } catch (MyException e){ System.out.println(“3”); } finally { System.out.println(“2”); } void MyTest(int y) { try { System.out.prinln(“6”); Test(y); System.out.println(“7”); } catch (YourException e) { System.out.println(“5”); } EXERCISE: what will be the ouput for a) MyTest(0); b) MyTest(1); c) MyTest(2); d) MyTest(3);

Applets cont.

Applet parameters.... balls=Integer.parseInt(getParameter(“BALLS"));.... BouncingBall

Why is it flickering? “repaint” thread repaint requests update() clears screen calls paint()

Double buffering “repaint” thread repaint requests update() calls paint() clears second-screen draws everything on the second-screen copies second-screen to the screen

BouncingBall revisited Image offscreenImage; Graphics offscreenGraphics; offscreenImage = createImage(width,height); offscreenGraphics = offscreenImage.getGraphics(); offscreenGraphics.setColor(Color.black); offscreenGraphics.fillRect(0,0,width,height); g.drawImage(offscreenImage, 0, 0, this); BouncingBall