Java Based Techhnology

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

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Java Threads CS Introduction to Operating Systems.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
Threads.
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.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
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.
Java 3: Odds & Ends Advanced Programming Techniques.
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.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
THREAD MODEL.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
Multithreading programming Pavan d.m.
Threads Chate Patanothai.
Exception Handling Visit for more Learning Resources.
ITEC324 Principle of CS III
Multithreading.
Multithreading 2 Lec 24.
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Java Thread.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Based Techhnology Java Threads 12/27/2018 Java thread Applications

Java thread Applications Introductions Java defines a model of concurrency and synchronization and is thus a concurrent object-oriented language. The unit of concurrency is a thread. A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. 12/27/2018 Java thread Applications

Java thread Applications Introductions Threads are a way for a program to fork or split itself into two or more simultaneously running tasks. On a single processor, Multithreading occurs by time-division multiplexing (time slicing); The processor switches between different threads. On a multiprocessor or multi-core system, multiple threads can run simultaneously on different processors or cores 12/27/2018 Java thread Applications

Java thread Applications Introductions A thread executes statements and moves from object to object as it executes method invocations. Threads can be dynamically created, pre-empted, suspended, resumed and terminated. Each thread belongs to a thread group specified at thread creation time 12/27/2018 Java thread Applications

Java thread Applications Thread Creations Package java.lang.Thread 1 st Method Public class Thread extends Thread Runnable{ } 2nd Method Public class Thread implements Runnable { } 12/27/2018 Java thread Applications

Java thread Applications It allows to perform more than one task at a time. Resource sharing between threads is easy. It maximizes CPU utilization It reduces the complexity of large programs. It increases the speed of execution. 12/27/2018 Java thread Applications

Java thread Applications Examples class HelloThread extends Thread { public void run() { try{ for ( ; ; ) { System.out.println("hello"); sleep(1000); } }catch(Exception e){} } } public class ThreadTest { public static void main(String[] args) throws Exception { Thread hello = new HelloThread(); hello.start(); System.out.println("Sorry, I must be leaving"); } } 12/27/2018 Java thread Applications

Java thread Applications Thread States 12/27/2018 Java thread Applications

Java thread Applications Thread States New Thread  Creates a new thread but does not start it, hereby leaving the thread in the New Thread state. Exp: Thread myThread = new MyThreadClass(); Runnable Exp:Thread myThread = new MyThreadClass();myThread.start(); The start method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run method. At this point the thread is in the "Runnable" state. 12/27/2018 Java thread Applications

Java thread Applications Thread States Not Runnable  Someone invokes its sleep method. Someone invokes its suspend method. The thread uses its wait method to wait on a condition variable. The thread is blocking on I/O. Dead A thread can die in two ways: either from natural causes, or by being killed (stopped). A thread dies naturally when its run method exits normally. 12/27/2018 Java thread Applications

Java thread Applications Thread States Example Thread myThread = new MyThreadClass(); myThread.start(); try { Thread.sleep(10000); } catch (InterruptedException e) {} myThread.stop(); 12/27/2018 Java thread Applications

Java thread Applications Simple Program public class Threads{   public static void main(String[] args){   Thread th = new Thread();   System.out.println("Numbers are printing line by line after 5 seconds : ");   try{   for(int i = 1;i <= 10;i++)     {   System.out.println(i);   th.sleep(5000);   }   }   catch(InterruptedException e){     System.out.println("Thread interrupted!");   e.printStackTrace();   }   } } 12/27/2018 Java thread Applications

Java thread Applications Life Cycles Of Thread 12/27/2018 Java thread Applications

Java thread Applications Life Cycles Of Thread New state – after the Thread creation it is in this state but before the start() method invocation. ( thread is considered not alive)       Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.  12/27/2018 Java thread Applications

Java thread Applications Life Cycles Of Thread Running state – Is currently executing. The scheduler select a thread from runnable pool.       Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. Blocked – A thread can enter in this state because of waiting the resources that are hold by another thread. 12/27/2018 Java thread Applications

Creation of Multithread class MyThread extends Thread{   MyThread(String s){     super(s);     start();   }   public void run(){     for(int i=0;i<5;i++){       System.out.println("Thread Name  :"               +Thread.currentThread().getName());       try{         Thread.sleep(1000);       }catch(Exception e){}     }   } }   public class MultiThread1{   public static void main(String args[]){     System.out.println("Thread Name :"            +Thread.currentThread().getName());       MyThread m1=new MyThread("My Thread 1");     MyThread m2=new MyThread("My Thread 2");   } } 12/27/2018 Java thread Applications

Java thread Applications Output C:\nisha>javac MultiThread1.java C:\nisha>java MultiThread1 Thread Name :main Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 Thread Name :My Thread 1 Thread Name :My Thread 2 12/27/2018 Java thread Applications

Using Runnable Interfaces class MyThread1 implements Runnable{   Thread t;   MyThread1(String s)  {     t=new Thread(this,s);     t.start();   }     public void run()  {     for(int i=0;i<5;i++) {       System.out.println("Thread Name  :"+Thread.currentThread().getName());       try {       Thread.sleep(1000);       }catch(Exception e){}     }   } } public class RunnableThread1{   public static void main(String args[])  {     System.out.println("Thread Name :"+Thread.currentThread().getName());       MyThread1 m1=new MyThread1("My Thread 1");     MyThread1 m2=new MyThread1("My Thread 2");   } } 12/27/2018 Java thread Applications

Java thread Applications Thread Methods  Method  Return Type  Description  currentThread( )  Thread  Returns an object reference to the thread in which it is invoked.  getName( )  String  Retrieve the name of the thread object or instance.  start( )  void  Start the thread by calling its run method.  run( )  This method is the entry point to execute thread, like the main method for applications.  sleep( )  Suspends a thread for a specified amount of time (in milliseconds).   isAlive( )  boolean  This method is used to determine the thread is running or not. 12/27/2018 Java thread Applications

Java thread Applications Thread Methods  Method  Return Type  Description  activeCount( )  int  Returns the number of active threads in a particular thread group and all its subgroups.  interrupt( )  void  Method interrupt the threads on which it is invoked.  yield( )  By invoking this method the current thread pause its execution temporarily and allow other threads to execute.  join( )  This method and  join(long millisecond) Throws Interrupted Exception.  These two methods are invoked on a thread, are not returned until either the thread has completed or it is timed out respectively. 12/27/2018 Java thread Applications

Java thread Applications Java MultiThreading A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Is a specialized form of multitasking Types Process-based multitasking - allows your computer to run two or more programs concurrently Thread-based multitasking – Singleprogram can perform two or more tasks simultaneously 12/27/2018 Java thread Applications

Java thread Applications Context switch Thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. Rules A thread can voluntarily relinquish control By explicitly yielding, sleeping,or blocking on pending I/O. Highest-priority thread that is ready to run is given CPU. A thread can be preempted by a higher-priority thread. Lower-priority thread that does not yield the processor is simply preempted—(no matter what it is doing—by a higher-priority thread.) Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. 12/27/2018 Java thread Applications

Java thread Applications Examples // Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } } 12/27/2018 Java thread Applications

Java thread Applications Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to the others Thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads . Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.   12/27/2018 Java thread Applications

Java thread Applications Thread Priorities Constant  Description  Thread.MIN_PRIORITY  The maximum priority of any thread (an int value of 10)  Thread.MAX_PRIORITY  The minimum priority of any thread (an int value of 1)  Thread.NORM_PRIORITY  The normal priority of any thread (an int value of 5) 12/27/2018 Java thread Applications

Thread Priorities Methods  Description  setPriority()  This is method is used to set the priority of thread.  getPriority()  This method is used to get the priority of thread. Example 12/27/2018 Java thread Applications

Java thread Applications Priority Examples Example 1 Example2 Example3 12/27/2018 Java thread Applications

Thread Synchronization In a multithreaded environment, each thread has its own local thread stack and registers. If multiple threads access the same resource for read and write, the value may not be the correct value. Synchronization stages Signaled allows objects to access and modify data Non-signaled. state does allow accessing or modifying the data in the thread local stack Syntax synchronized(objectidentifier) { // Access shared variables and other shared resources } 12/27/2018 Java thread Applications

Thread Synchronization Java supports thread synchronization either by a synchronized method or by synchronized statement. Synchronization forces a thread to acquire a lock on an object before proceeding. If a thread already holds a lock on that object can continue. This avoids deadlocks- a thread reentering an object. 12/27/2018 Java thread Applications

Thread Synchronization methods Event: Event is a thread synchronization object used to set the signaled or non-signaled state. Signaled state may be manual or automatic depending on the event declaration. Mutex: Mutex is the thread synchronization object which allows to access the resource only one thread at a time. Only when a process goes to the signaled state are the other resources allowed to access. Semaphore: Semaphore is a thread synchronization object that allows zero to any number of threads access simultaneously. 12/27/2018 Java thread Applications

Java thread Applications DeadLock A situation where a thread is waiting for an object lock that holds by second thread, and this second thread is waiting for an object lock that holds by first thread, this situation is known as Deadlock. 12/27/2018 Java thread Applications

Java thread Applications Example 12/27/2018 Java thread Applications

Java thread Applications Exercise 1. Write a program using Simple threaded application 2. Write a program to create two threads where one prints even numbers & the other prints odd numbers 3. Write a program to print “welcome” using runnable interface 4. Create 2 threads & set the priority for the threads . 12/27/2018 Java thread Applications