Software Practice 1 - Multithreading

Similar documents
JAVA - MULTITHREADING

Unit 5 - Exception Handling & Multithreaded

Unit - IV Multi-Threading

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Module - 4 Multi-Threaded Programming

04-Java Multithreading

Multithread Computing

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

JAVA. Lab 12 & 13: Multithreading

7. MULTITHREDED PROGRAMMING


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

Multithreading Pearson Education, Inc. All rights reserved.

Concurrent Programming using Threads

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

Amity School of Engineering

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

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

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

Unit III Rupali Sherekar 2017

Software Practice 1 Basic Grammar

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

CS360 Lecture 12 Multithreading

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

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

Threads Chate Patanothai

Programming Java. Multithreaded Programming

Object-Oriented Programming Concepts-15CS45

Synchronized Methods of Old Versions of Java

Object Oriented Programming. Week 10 Part 1 Threads

UNIT V CONCURRENT PROGRAMMING

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

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

CIS233J Java Programming II. Threads

Multithreaded Programming

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

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

Concurrent Computing CSCI 201 Principles of Software Development

Multi-threading in Java. Jeff HUANG

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

EDAF65 Processes and Threads

EDA095 Processes and Threads

G.PULLAIAH COLLEGE OF ENGINEERING AND TECHNOLOGY

CS 556 Distributed Systems

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

public class Shared0 { private static int x = 0, y = 0;

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Multithreaded Programming

Basics of. Multithreading in Java

Animation Part 2: MoveableShape interface & Multithreading

Software Practice 1 - Error Handling

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

Software Practice 1 - Socket

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

Threads in Java (Deitel & Deitel)

EDA095 Processes and Threads

COE518 Lecture Notes Week 7 (Oct 17, 2011)

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

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

Multithreading using Java. Dr. Ferdin Joe John Joseph

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

Techniques of Java Programming: Concurrent Programming in Java

Software Practice 1 - File I/O

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

What is a thread anyway?

Software Practice 1. Course Overview Lecture Schedule Today s Task Contact

CS 351 Design of Large Programs Threads and Concurrency

Introduction to Java 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

Dining philosophers (cont)

Performance Throughput Utilization of system resources

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

MULTI-THREADING

Advanced Concepts of Programming

Time-Sharing Operating Systems. EDA095 Processes and Threads. Process Creation. The Content of a Process

Java Threads. Introduction to Java Threads

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

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

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

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

CERTIFICATION OBJECTIVES

Chapter 32 Multithreading and Parallel Programming

JOURNAL OF OBJECT TECHNOLOGY

Parallel Programming Practice

Chapter 19 Multithreading

Threads Questions Important Questions

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Software Practice 1 - OOP (3) API

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Parallel Programming Practice

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

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Java Threads. COMP 585 Noteset #2 1

CSCD 330 Network Programming

Sat 1/6/2018. MULTITHREAD... 5 THREADS What do you mean by Multithreaded program?... 5 LIFE CYCLE OF A THREAD:... 5

Transcription:

Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee (42) (43) 1

2 Thread The smallest sequence of programmed instructions that can be managed independently by a scheduler of OS The implementation of threads and process differs between operating systems, but in most cases a thread is a component of a process

Life Cycle of Thread 3

4 Life Cycle of Thread New A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) A runnable thread enters the terminated state when it completes its task or otherwise terminates.

5 Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

6 Create a Thread by Implementing a Runnable Interface If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface Step 1 : implement a run() method Public void run() Step 2 : instantiate a Thread object Thread(Runnable threadobj, String threadname); Step 3 : Call start() void start();

7 Example class RunnableDemo implements Runnable { private Thread t; private String threadname; RunnableDemo( String name) { threadname = name; System.out.println("Creating " + threadname ); public void run() { System.out.println("Running " + threadname ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadname + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); catch (InterruptedException e) { System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () { System.out.println("Starting " + threadname ); if (t == null) { t = new Thread (this, threadname); t.start ();

8 Example (cont d) public class TestThread { public static void main(string args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start();

9 Create a Thread by Extending a Thread Class create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 : override run() method public void run() Step 2 : call start() method void start();

10 Example class ThreadDemo extends Thread { private Thread t; private String threadname; ThreadDemo( String name) { threadname = name; System.out.println("Creating " + threadname ); public void run() { System.out.println("Running " + threadname ); try { catch (InterruptedException e) { System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () { System.out.println("Starting " + threadname ); if (t == null) { t = new Thread (this, threadname);t.start (); for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadname + ", " + i); // Let the thread sleep for a while. Thread.sleep(50);

11 Example (cont d) public class TestThread { public static void main(string args[]) { ThreadDemo T1 = new ThreadDemo( "Thread-1"); T1.start(); ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start();

Thread Methods Sr.No. 1 2 3 4 5 6 7 8 Method & Description public void start() Starts the thread in a separate path of execution, then invokes the run() method on this T hread object. public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked onthat Runnable object. public final void setname(string name) Changes the name of the Thread object. There is also a getname() method for retrieving the name. public final void setpriority(int priority) Sets the priorityof this Thread object. The possible values are between 1 and 10. public final void setdaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block untilthe second thread terminatesor the specified number of milliseconds passes. public void interrupt() Interruptsthisthread, causing it to continue execution if it was blocked for anyreason. public final boolean isalive() Returns true if the thread is alive, which is any time after the thread has been started but before it runsto completion. 12

13 Thread Static Method Sr.No. 1 2 Method & Description public static void yield() Causes the currently running thread to yield to any other threads of the same priority t hat are waiting to be scheduled. public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of millis econds. 3 public static boolean holdslock(object x) Returns true if the current thread holdsthe lock on the given Object. 4 public static Thread currentthread() Returns a reference to the currently running thread, which is the thread that invokes th is method. 5 public static void dumpstack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

14 Major Java Multithreading Concepts While doing Multithreading programming in Java, you would need to have the following concepts very handy What is thread synchronization? Handling interthread communication Handling thread deadlock Major thread operations

15 Synchronized Synchronized method public synchronized void set() { Synchronized block public void method() { synchronized (object) {

16 Wait & Notify Wait() The wait() method causes the current thread to wait indefinitely until another thread either invokes notify () for this object or notifyall(). Notify() The notify() method is used for waking up thread th at are waiting for an access to this object s monitor.

17 [Lab Practice] Producer - Consumer Problem There are two process(thread) producer and consumer, who are share common fixed-size buffer. The producer s job is to generate data and put it into buffer At the same time, consumer is consuming the data, one piece at a time.

18 Producer - Consumer Buffer size == 5 Produce (consume) 10 data. (0 to 9) Warning! Cannot consume the data if buffer is empty Cannot produce the data if buffer is full Hint Wait and Notify BlockingQueue

19 Example of Output Output: Start: Producer Start: Consumer Produced: 0 Produced: 1 Consumed: 0 Produced: 2 Consumed: 1 Consumed: 7 Produced: 9 Consumed: 8 Consumed: 9

20 [Submit] Upload to i-campus Compress your Producer.java & Consumer.java to zip file File name: studentid_lab8.zip Due date Today 23:59:59 Class 42 (05/21 Monday) Penalty: -10% of each lab score per one day