© 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.

Slides:



Advertisements
Similar presentations
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Advertisements

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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
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.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
Java: Animation Chris North cs3724: HCI. Animation? Changing graphics over time Examples: cartoons Clippy, agents/assistants Hour glass Save dohicky Progress.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
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)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
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
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
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.
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.
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.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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
Multithreaded applets
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreaded Programming in Java
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Threads and Multithreading
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Chapter 15 Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

© 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 and syntax of the Thread, Date, Calendar, and GregorianCalendar classes and the methods used to manipulate them u Display the current date and time on an applet Objectives

© Wang Bin 2004 u Definition of a Thread:  A process is divided into several tasks. Each task is divided into smaller units called threads  A thread can be defined as a single sequential flow of control within a program  Every program has at least one thread that is called the primary thread  The microprocessor allocates memory to the processes that you execute. Each process occupies its own address space (memory)  All the threads in a process share the same address space Threads

© Wang Bin 2004  A process that is made of only one thread is said to be single-threaded  A process having more than one thread is said to be multithreaded. The multiple threads in the process run at the same time, perform different tasks, and interact with each other  Java has built-in support for threads. A major portion of the Java architecture is multithreaded Definition of Multithreading

© Wang Bin 2004 An additional feature has to be added to the Customer details applet. The current date and time has to be displayed on the status bar of the applet. Write the code. Problem Statement

© Wang Bin 2004  The Thread Class:  The java.lang.Thread class is used to construct and access the individual threads in a multithreaded application  You can make your applications and classes run in separate threads by extending the Thread class  Syntax: public class extends Thread Identify the mechanism to be used for displaying the date and time

© Wang Bin 2004  The Runnable Interface:  When a program needs to inherit from another class besides the Thread class, you need to implement the Runnable interface  The Runnable interface consists of a single method run(), which is executed when the thread is activated  Syntax for implementing the Runnable interface public class extends implements Runnable Identify the mechanism...(Contd.)

© Wang Bin 2004 u Life Cycle of a Thread:  When an instance of the Thread class is created, a thread enters the new thread state  When the start() method of the thread is invoked, the thread enters the runnable state  A thread is said to be in the not runnable state if it is sleeping, waiting, or being blocked by another thread  A thread is put into the sleeping mode with the sleep() method Identify the mechanism...(Contd.)

© Wang Bin 2004  Syntax of the sleep() method: sleep(long t);  In the syntax, t is the number of milliseconds for which the thread is inactive  A thread object is dead if the loop in run() method is complete or a null value is assigned to the thread  The Date Class  The Date class encapsulates the system date and time information Identify the mechanism...(Contd.)

© Wang Bin 2004  The Calendar Class:  The Calendar class implements the methods that were present in the earlier version of the Date class  The get() Method:  The get() method of the Calendar class is used to extract the date, the month, or the year from a given date  Syntax of the get() method: String get(int field); Identify the mechanism...(Contd.)

© Wang Bin 2004  Fields in the Calendar Class: FieldsReturn Values static int HOUR Hour of the time static int MINUTE Minutes of the time static int SECOND Seconds of the time static int DATE Date portion of the date static int MONTH Month portion of the date static int YEAR Year portion of the date Identify the mechanism...(Contd.)

© Wang Bin 2004  The GregorianCalendar Class:  The GregorianCalendar class is extended from the Calendar class  It supports calendar operations for most parts of the world  The setTime() Method:  The setTime() method takes a Date object as an argument  It updates the GregorianCalendar object with the current date Identify the mechanism...(Contd.)

© Wang Bin 2004  Syntax of the setTime() method: setTime(Date date); u Result:  The applet will need to show the date and time simultaneously with the other controls, therefore use the following: Thread class Runnable interface Date class Calendar class GregorianCalendar class Identify the mechanism...(Contd.)

© Wang Bin 2004 public class CustomerApplet extends JApplet implements Runnable { Thread datimeThread; Date date; GregorianCalendar calendar; String strDate, strTime, strStatus; public void init() { createAppletContent(); //Method for Applet Layout is called } protected void createAppletContent() { candidateDetail(); // contents of the applet } public void candidateDetail() { datimeThread = new Thread(this); //Initialize thread datimeThread.start(); //Starting thread } …… } Codes

© Wang Bin 2004 public void run() // body of the thread { while(datimeThread != null) { display() ; // This method displays date try { datimeThread.sleep(1000); } catch(InterruptedException e) { showStatus("Thread interrupted"); } } //end of while loop } //end of run method Codes

© Wang Bin 2004 public void display() //displays date and time on the status bar { date = new Date(); calendar = new GregorianCalendar(); calendar.setTime(date); strTime = calendar.get(Calendar.HOUR)+":" + calendar.get(Calendar.MINUTE)+":"+ calendar.get(Calendar.SECOND); strDate = calendar.get(Calendar.MONTH)+"/"+ calendar.get(Calendar.DATE)+"/"+ calendar.get(Calendar.YEAR); strStatus=strTime+" "+strDate; showStatus(strStatus); } }//end of program Codes

© Wang Bin 2004 u When two threads share data, we must guarantee one thread can not change data which another thread use. u We use keyword synchronized to resolve it. Thread Synchronization

© Wang Bin 2004 class MyThread extends Thread { static String message[] = {"I", "Love","Java","Very","Much."}; public MyThread(String id) { super(id); } public void run() { Sync.displayList(getName(), message); } Examples

© Wang Bin 2004 void waiting() { try { sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } Examples (Contd.)

© Wang Bin 2004 class Sync { public static synchronized void displayList(String name, String list[]) { for(int i = 0; i < list.length; ++i) { MyThread thread = (MyThread)Thread.currentThread(); thread.waiting(); System.out.println(name + list[i]); } Examples (Contd.)

© Wang Bin 2004 class ThreadSync { public static void main(String args[]) { MyThread thread1 = new MyThread("Thread 1 : "); MyThread thread2 = new MyThread("Thread 2 : "); thread1.start(); thread2.start(); } Examples (Contd.)

© Wang Bin 2004 Result

© Wang Bin 2004 If no synchronized, Result:

© Wang Bin 2004 u In this lesson, you learned that:  You can execute multiple tasks within a program using threads  A thread, like a program, has a beginning, a sequence of steps, and an end. However, it is not a program on its own but runs within a process of a program. A process is an executing instance of a program. A thread is also known as a lightweight process or the execution context  A process having more than one thread is said to be multithreaded. The multiple threads in a process run simultaneously, perform different tasks, and interact with each other Summary

© Wang Bin 2004  The java.lang.Thread class is used to construct and access the individual threads in a multithreaded application  Applets extend from the JApplet class. Since Java does not support multiple inheritance, you cannot inherit a class from the JApplet as well as the Thread class. Java provides the Runnable interface to solve this problem. The Runnable interface consists of a single method run(), which is executed when the thread is activated Summary (Contd.)

© Wang Bin 2004  The life cycle of a thread consists of four stages: New thread Not Runnable Runnable Dead  When an instance of the Thread class is created, the thread enters the new thread state  The start() method is responsible for starting a thread. When the start() method of the thread is invoked, the thread enters the runnable state Summary (Contd.)

© Wang Bin 2004  The activities to be performed by a thread are coded in the run() method  A thread is said to be in the not runnable state if it: Is sleeping, Is waiting, or Is being blocked by another thread  A thread is put into the sleeping mode with the sleep() method Summary (Contd.)

© Wang Bin 2004  Invoking the stop() method of an applet kills a thread. The isAlive() method of the Thread class is used to determine whether a thread has been started or stopped  The Date class is responsible for encapsulating the date and time  The Calendar class implements the date methods that were present earlier in the Date class  The GregorianCalendar class is extended from the Calendar class. It supports calendar operations for most parts of the world Summary (Contd.)

© Wang Bin 2004  The setTime() method sets the calendar's current time with the given date  The get() method is used to extract the date, month, and year from the Calendar variable  The showStatus() method displays a message on the status bar  Thread Synchronization  Keyword synchronized Summary (Contd.)