CIS233J Java Programming II. Threads

Similar documents
CS 556 Distributed Systems

Object Oriented Programming. Week 10 Part 1 Threads

Note: Each loop has 5 iterations in the ThreeLoopTest program.

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

REVIEW OF COMMONLY USED DATA STRUCTURES IN OS

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreading Pearson Education, Inc. All rights reserved.

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Lecture 17: Threads and Scheduling. Thursday, 05 Nov 2009

Unit 8: Threads. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

By: Abhishek Khare (SVIM - INDORE M.P)

Concurrent Programming

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Definition: A thread is a single sequential flow of control within a program.

Object Oriented Programming (II-Year CSE II-Sem-R09)

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

7. MULTITHREDED PROGRAMMING

Threads Chate Patanothai

Multithreading in Java Part 2 Thread - States JAVA9S.com

CHAPTER 2: PROCESS MANAGEMENT

Operating Systems Design Fall 2010 Exam 1 Review. Paul Krzyzanowski

Unit - IV Multi-Threading

Java s Implementation of Concurrency, and how to use it in our applications.

CMSC 132: Object-Oriented Programming II. Threads in Java

Amity School of Engineering

SMD149 - Operating Systems

Software Practice 1 - Multithreading

Unit III Rupali Sherekar 2017

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

Multithread Computing

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Chapter 6: CPU Scheduling

Concurrent Programming

Concurrent Programming. Implementation Alternatives. Content. Real-Time Systems, Lecture 2. Historical Implementation Alternatives.

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

Chapter 07: Instruction Level Parallelism VLIW, Vector, Array and Multithreaded Processors. Lesson 06: Multithreaded Processors

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Concurrent Programming using Threads

Performance Throughput Utilization of system resources

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

CS 571 Operating Systems. Midterm Review. Angelos Stavrou, George Mason University

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Multithreaded Programming

Unit 5 - Exception Handling & Multithreaded

Process Scheduling. Copyright : University of Illinois CS 241 Staff

Concurrent Computing CSCI 201 Principles of Software Development

8: Scheduling. Scheduling. Mark Handley

Lecture 2 Process Management

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

Class average is Undergraduates are performing better. Working with low-level microcontroller timers

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

1.1 CPU I/O Burst Cycle

Contents. 6-1 Copyright (c) N. Afshartous

Synchronization

CSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Project 1 (document version 1.3) Process Simulation Framework

OPERATING SYSTEMS. UNIT II Sections A, B & D. An operating system executes a variety of programs:

CSCI-GA Operating Systems Lecture 3: Processes and Threads -Part 2 Scheduling Hubertus Franke

Process a program in execution; process execution must progress in sequential fashion. Operating Systems

Scheduling in the Supermarket

Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation

Last class: Today: CPU Scheduling. CPU Scheduling Algorithms and Systems

Java Threads. Written by John Bell for CS 342, Spring 2018

ECE 7650 Scalable and Secure Internet Services and Architecture ---- A Systems Perspective. Part I: Operating system overview: Processes and threads

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

JAVA. Lab 12 & 13: Multithreading

CS Mid term Exam Maximum points 100; Maximum time allowed: 75 minutes

Scheduling policy. Reference: ULK3e 7.1. Scheduling in Linux 1 / 20

Processes and Threads

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS

Properties of Processes

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Lecture 7: Process & Thread Introduction

Unit 3 : Process Management

UNIT V CONCURRENT PROGRAMMING

OPERATING SYSTEMS: Lesson 4: Process Scheduling

Last Class: CPU Scheduling. Pre-emptive versus non-preemptive schedulers Goals for Scheduling: CS377: Operating Systems.

Chapter 5: CPU Scheduling

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

Processes and Threads

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey

Getting to know you. Anatomy of a Process. Processes. Of Programs and Processes

UNIT:2. Process Management

Interactive Scheduling

Two Level Scheduling. Interactive Scheduling. Our Earlier Example. Round Robin Scheduling. Round Robin Schedule. Round Robin Schedule

04-Java Multithreading

Processes and Non-Preemptive Scheduling. Otto J. Anshus

Threads in Java (Deitel & Deitel)

Transcription:

CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential flow of control within a program. A thread is not a program and cannot run on its own. Think of a thread as a task that performs a specific job. The advantage of breaking a program into threads is that they can run together (concurrently). Without threads, the tasks of a program are run one after another and the entire program can take longer to run. With threads, you can do multi-tasking, which means the entire program can run quicker. For example, you could start a thread that does some file writing and another thread that does some reading from a database; both can be running at the same time. Difference between a thread and a process "Some texts use the name lightweight process instead of thread. A thread is similar to a real process in that a thread and a running program are both a single sequential flow of control. However, a thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment." "As a sequential flow of control, a thread must carve out some of its own resources within a running program. (It must have its own execution stack and program counter for example.) The code running within the thread works only within that context. Thus, some other texts use execution context as a synonym for thread." (Source: Thread's run Method You must supply a run method for your thread. There are two ways to do this: subclass the Thread class and override the run method

implement the runnable interface and provide a run method First way: public class YourClass extends Thread public void run() //your code here; whatever you want the thread to do Basically all you're doing here is to create a subclass (child class) from the Thread parent class. In your class, override the Thread class run method. In the run method, put all the code that you want your thread to perform. Second way: public class YourClass implements Runnable public void run() //your code here; whatever you want the thread to do In order to understand this method, you need to understand interfaces. There is information on this in the Course Content. Be sure to read it first. Here, you are implementing the Runnable interface and providing a run method. The run method is the same as described above; it contains the code you want to run in your thread. Creating a Thread As with all things in Java, you create an object based on a class. So here, you create an object from the thread class that you created. You first create a Thread object and give it a name: YourThreadClass threadname = new YourThreadClass(); This creates a thread object and Java puts it in the "New Thread" state. That is, it is not running. You must start it.

Starting a Thread The start method does three things: creates the system resources necessary to run the thread schedules the thread to run calls the thread's run method. threadname.start(); Remember that a system with a single CPU, such as Windows, can only handle one thread at a time. So if you start two threads, the processor is actually going back and forth between them, doing what they want. Because the processor is so fast, it appears that the threads are running at the same time; but they are not. They are being given slices of time by the processor. Making a Thread Not Runnable A thread becomes Not Runnable when one of these events occurs: the sleep method is invoked it calls the wait method to wait for a specific condition to be satisfied it is waiting on I/O threadname.sleep(1000); Sleeping threads do not run even if the processor is available. The thread will wake up when the number of milliseconds elapses (1000 in the above example.) Threads waiting for I/O wait until the I/O completes. Stopping a Thread A thread stops (ends) when it's run method is completed. This is also known as the thread dying (a natural death, as it were.) There is also a stop method for a thread. The isalive Method

"The isalive method returns true if the thread has been started and not stopped. If the isalive method returns false, you know that the thread either is a New Thread or is Dead. If the isalive method returns true, you know that the thread is either Runnable or Not Runnable. You cannot differentiate between a New Thread or a Dead thread. Nor can you differentiate between a Runnable thread and a Not Runnable thread." (Source: Understanding Thread Priority "Previously, this lesson claimed that threads run concurrently. While conceptually this is true, in practice it usually isn't. Most computer configurations have a single CPU, so threads actually run one at a time in such a way as to provide an illusion of concurrency. Execution of multiple threads on a single CPU, in some order, is called scheduling. The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling. This algorithm schedules threads based on their priority relative to other runnable threads. When a Java thread is created, it inherits its priority from the thread that created it. You can also modify a thread's priority at any time after its creation using the setpriority method. Thread priorities are integers ranging between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class). The higher the integer, the higher the priority. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. Only when that thread stops, yields, or becomes not runnable for some reason will a lower priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion. The chosen thread will run until one of the following conditions is true: A higher priority thread becomes runnable. It yields, or its run method exits. On systems that support time-slicing, its time allotment has expired. Then the second thread is given a chance to run, and so on, until the interpreter exits. The Java runtime system's thread scheduling algorithm is also preemptive. If at any time a thread with a higher priority than all other runnable threads becomes runnable, the runtime system chooses the new higher priority thread for execution. The new higher priority thread is said to preempt the other threads." (Source: There is a setpriority method for a thread.

Summary Most computers have only one CPU, so threads must share the CPU with other threads. The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling. Each Java thread is given a numeric priority between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class). At any given time, when multiple threads are ready to be executed, the thread with the highest priority is chosen for execution. Only when that thread stops, or is suspended for some reason, will a lower priority thread start executing. Scheduling of the CPU is fully preemptive. If a thread with a higher priority than the currently executing thread needs to execute, the higher priority thread is immediately scheduled. The Java runtime will not preempt the currently running thread for another thread of the same priority. In other words, the Java runtime does not time-slice. However, the system implementation of threads underlying the Java Thread class may support time-slicing. Do not write code that relies on time-slicing. In addition, a given thread may, at any time, give up its right to execute by calling the yield method. Threads can only yield the CPU to other threads of the same priority--attempts to yield to a lower priority thread are ignored. When all the runnable threads in the system have the same priority, the scheduler chooses the next thread to run in a simple, non-preemptive, round-robin scheduling order. Summary is from: http://java.sun.com/docs/books/tutorial/essential/threads/index.html