Thread Examples. Runnable Interface Runnable defines only one abstract method; Public void run(); Thread also implements Runnable interface. Why does.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
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.
Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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.
29-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Threads CS Introduction to Operating Systems.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
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.
Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS12420 – Swing and threads Lynda Thomas
Week 3, Day 1: Processes & Threads Return Quiz Processes Threads Lab: Quiz Lab 3: Strategy & Factory Patterns! SE-2811 Slide design: Dr. Mark L. Hornick.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
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.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Threading and Concurrency COM379T John Murray –
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
1 CSCD 330 Network Programming Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 9 Client-Server Programming.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Threads and Multithreading. Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three general approaches:
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
CSCD 330 Network Programming
Multithreaded applets
Chapter 13: Multithreading
Multi Threading.
Threads and Multithreading
Object-Orientated Analysis, Design and Programming
Threads and Multithreading
Threads and Multithreading
Principles of Software Development
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Java Thread.
Chapter 15 Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Threads.
Gentle Introduction to Threads
Lecture 19 Threads CSE /6/2019.
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Thread Examples

Runnable Interface Runnable defines only one abstract method; Public void run(); Thread also implements Runnable interface. Why does java provide this weird interface? Suppose we want to make an applet named WantToBeThread and we want to have a thread inside this applet. In other words, we want WantToBeThread to share its method with another thread. This is not an easy situation since a class can not extend two or more classes. The solution is to implement Runnable interface with some trick.

Runnable Interface cont. Remember that we need a thread anyway. Let’s call the thread as RunForYou. The idea is to make run() method of WantToBeThread applet as the starting point of RunForYou. This can be viewed as replacing the run() method of RunForYou with that of WantToBeThread applet. As a result, when WantToBeThread calls start() of RunForYou, run() of WantToBeThread will be called eventually.

class WantToBeThread extends Applet implments Runnable { Thread RunForYou; public void start() { if ( RunForYou == null ) { RunForYou = new Thread(this); // Note this is Runnable RunForYou.start(); } public void run() { // RunForYou runs here!!! } public void stop() { RunForYou = null; // Will be explained later. }

Server Example In client/server model, the server part is generally designed to wait indefinitely for a request from a client. Once a request comes in, the server executes the corresponding service routine for the request. Let’s suppose we implement a server (can be any type of server), which is single threaded. This means when the server is in the middle of processing a client request, no further request gets serviced until the server finishes with the current request. This may result in servicing bottleneck especially the servicing routine contains any blocking call.

class Server extends JFrame implements ActionListener { Server() { Container pane = getContentPane(); JButton button = new JButton("Request"); button.addActionListener(this); pane.add(button); setSize(300,200); setVisible(true); } public void actionPerformed(ActionEvent evt) { do_service(); } public static void main(String args[]) { new Server(); } private void do_service() { for (int I=0; I<10; I++) { try { Thread.sleep(1000); } catch (InterruptedException ie) {} System.out.println(“count down “ + (10 – I)); }

class ServiceHandler extends Thread { int req; ServiceHandler(int req) { this.req = req; } public void run() { for (int i=0; i<10; i++) { try { sleep(1000); }catch (InterruptedException ie) { } System.out.println("handling req " + req + ":" + (10-i)); } System.out.println(" handling req " + req + " done"); } class Server2 implements ActionListener { int req=0; ……… public void actionPerformed(ActionEvent evt) { new ServiceHandler(req++).start(); }

class Server3 extends JFrame implements ActionListener,Runnable { Server3() { // The same constructor as Server} public void actionPerformed(ActionEvent evt) { new Thread(this).start(); } public void run() { for (int i=0; i<10; i++) { try { Thread.sleep(1000); } catch (InterruptedException ie) {} System.out.println("handling request:" + (10-i)); } System.out.println(" handling request done"); } public static void main(String args[]) { new Server3(); }

Test Prime Number Often we want to solve a problem by dividing it into a set of smaller problems. Let’s suppose we want to build a program that tests whether the given number is a prime number. Even though there are good algorithms that do the job efficiently, we are going to use the very basic one here. (Divide by every number within the range) To demonstrate the power of parallel programming, we split the range into several sub ranges and let different threads test different sub ranges.

public class PrimeChecker { public static void main(String args[]) { long number = Long.parseLong(args[0]); int interval = (int)(number/100) + 1; for (int i=0; i<interval; i++) { new CheckRange(i*100,number).start(); }

class CheckRange extends Thread { long base,number; CheckRange(long base, long number) { if ( base == 0 ) this.base = 2; else this.base = base; this.number=number; } public void run() { for (long i=base; i<base+100; i++) { if ( number%i == 0 ) { System.out.println(number + " is divisible by " + i + " found by " + getName()); break; } yield(); }