Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.

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

Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
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.
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
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
Threads. Story so far  Our programs have consisted of single flows of control Flow of control started in the first statement of method main() and worked.
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.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
© 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
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
THREAD Subject:T0934 / Multimedia Programming Foundation Session:3 Tahun:2009 Versi:1/0.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Threads.
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Java Programming Language
Multithreaded Programming in Java
Multithreading in Java
Threads Chate Patanothai.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads in Java James Brucker.
Multithreading in java.
Threads and Multithreading
Representation and Management of Data on the Internet
Threads.
Gentle Introduction to Threads
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable Example 2 Summary Exercises

Unit 142 What is a Thread? A thread is a single sequential flow of control within a program. At any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a program; a thread cannot run on its own. Rather, it runs within a program.

Unit 143 Multithreading Multiple threads can be executed at the same time within a single program. Such usage is called multi threading. Each thread may perform a different task in a single program Multiple threads create an illusion of several tasks being handled in parallel. Actually the processor allocates a fraction of its CPU cycle time to execute each thread.

Unit 144 Introduction: Where are Threads Used? Threads are used by virtually every computer user in the following instances: –In Internet browsers –In databases –In operating systems (for controlling access to shared resources etc) Benefits of threads –More productivity to the end user (such as responsive user interface) –More efficient use of the computer (such as using the CPU while performing input- output) –Sometimes advantageous to the programmer (such as simplifying program logic)

Unit 145 Creating Java Threads – Subclassing java.lang.Thread There are two ways to create threads in java. Assume you have a class “MyClass” which may contain several tasks to be executed as threads. One of the ways to create and execute a threaded application is as follows: –“MyClass” should be declared to be a subclass of java.lang.Thread. –“MyClass” should override the run method (public void run()) of class Thread. –An instance of the “MyClass” can then be instantiated and executed as a thread using the start() method. –Note that the code to be executed as thread should be in the run() method of “MyClass”. –The following example shows how this can be done.

Unit 146 Example 1 1.public class SimpleThread extends Thread { 2. private String title; 3. public SimpleThread(String str) { 4. this.title = str; 5. } public void run() { 8. for (int i = 0; i < 10; i++) { 9. System.out.println(i + " " + title); 10. try { 11. sleep((long)(Math.random() * 1000)); 12. } catch (InterruptedException e) {} 13. } 14. System.out.println("DONE! " + getName()); 15. } public static void main (String[] args) { 18. new SimpleThread("First Thread").start(); 19. new SimpleThread("Second Thread").start(); 20. } 21.}

Unit 147 Methods in java.lang.Thread The run() method contains the code which has to be executed as threads. The start() method is the method invoked in order for the threads to run in a multithreaded way. As soon as a call to start() is made, the thread is created and starts execution. Control returns back immediately to the next statement in the program while the thread may be in execution. Note that if a call new SimpleThread.run() is made, the run() method is executed in the current thread and the new thread is never started. public static void main (String[] args) { new SimpleThread("First Thread").start(); new SimpleThread("Second Thread").start(); } Thread is created and execution begins ……………….. ……………… Control returns back to the next statement before completion of the current statement.

Unit 148 Methods in java.lang.Thread – Contd. The sleep() method (public static void sleep(long millis) throws InterruptedException) makes the current thread inactive for a specified number of milliseconds. The InterruptedException is thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt() method in class Thread. The getName() (public final String getName()) method returns back the name of the current thread as a String. Every thread has a name (including anonymous threads) for identification purposes –More than one thread may have the same name –If a name is not specified when a thread is created, a new name is generated.

Unit 149 Creating Java Threads – Implementing java.lang.Runnable Another way to create and execute Java threads is as follows. Assume you have a class “MyClass” which may contain several tasks to be executed as threads. –“MyClass” should implement the interface java.lang.Runnable –“MyClass” should implement the run method (public void run()) of the interface Runnable –An instance of the Thread class can be created using an instance of “MyClass” as a parameter as follows: Thread t = new Thread(new MyClass()); –Now the run() method of “MyClass” can be executed as a thread by invoking the start() method using t.start(). –Note that the code to be executed as thread should be in the run() method of MyClass. –The following example shows how this can be done.

Unit 1410 Example 2 1.import javax.swing.*; 2.public class TimeThread extends JFrame implements Runnable { private JTextField sec, min, hrs; 5. private JPanel panel; 6. private int time = 0; public TimeThread() 9. { 10. super(“Time"); sec = new JTextField(3); sec.setEditable(false); //makes textfield uneditable 13. min = new JTextField(3); min.setEditable(false); 14. hrs = new JTextField(3); hrs.setEditable(false); panel = new JPanel(); panel.add(hrs); panel.add(min); panel.add(sec); getContentPane().add(panel); pack(); setVisible(true); 21. }

Unit 1411 Example – Contd. 22. public void run() 23. { 24. try { 25. while(true) { 26. Thread.sleep(1000); time++; 27. sec.setText(time%60 + ""); //Display seconds 28. min.setText((time – (time/3600)*3600)/60 + ""); //Display minutes 29. hrs.setText(time/ ""); //Display hours 30. } 31. } catch(InterruptedException e) {} 32. } public static void main(String[] args) 35. { 36. TimeThread t = new TimeThread(); 37. Thread mytime = new Thread(t); 38. mytime.start(); 39. } 40.}

Unit 1412 Summary A thread is a single sequential flow of control within a program. The run() method of the Thread class and/or the Runnable interface contains the code to be executed as a thread. There are two ways to create a thread: –Subclass the Thread class and override the run() method. –Provide a class that implements the Runnable interface and therefore implements the run() method. One of the main advantages of implementing the Runnable interface is that when our threaded application inherits from another class such as JFrame then we can make it as a threaded application by implementing the Runnable interface.

Unit 1413 Exercises Q. 1 In the first example replace the statement new SimpleThread(“First Thread”).start() with new SimpleThread(“First Thread”).run(). Observe the output and explain why it happens. Does your program take longer time to complete? Why? Q. 2 Implement the TimeThread as a CountDown timer, for example, the timer counts 1 hour down to zero seconds. Include any action at the end of the time, such as bringing up a JDialog informing that time is up.