Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples.

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

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
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.
Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.
Multithreading A thread is the flow of execution, from beginning to end, of a task in a program. With Java, you can launch multiple threads from a program.
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.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should.
Definitions Process – An executing program
1 Threads (Part II) Threads and Concurrency (Part II) Overview  Review of Previous Lecture.  Controlling Threads and Thread State.  Example 1: Creating.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Threads CS Introduction to Operating Systems.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
Multithreading.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
EE2E1. JAVA Programming Lecture 8 Multi-threading.
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.
1 Java Threads Instructor: Mainak Chaudhuri
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
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.
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
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.
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.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
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
Scis.regis.edu ● CS-434: Object-Oriented Programming Using Java Week 8 Dr. Jesús Borrego Adjunct Faculty Regis University 1.
Java Thread and Memory Model
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multi-Threading in Java
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.
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.
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.
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.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
Java Thread.
Chapter 15 Multithreading
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples

Unit 152 Introduction: What is a Thread? Just like human being can walk, talk, see, hear etc at the same time, computers can also download documents, print a file, receive concurrently Computers normally achieve concurrency using threads A thread or thread of control is a section of code executed independently of other threads of control within a single program Each thread has its own stack, priority, and virtual set of registers Every program has at least one thread Every Java applet or application is multithreaded

Unit 153 Single and Multithreaded Programs

Unit 154 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 155 Threads in Java Java is one of the few (the only?) languages that supports threads at the language level Writing multithreaded programs can be tricky: imagine reading three books by reading few words from each book for a few seconds repeatedly in succession Although Java is portable, its multithreading is platform dependent: a multithreaded program could behave differently on different platforms: Under Solaris implementation, an executing thread can run to completion or can be preempted by a higher priority thread On windows (NT and 98) threads are timesliced and preemption occurs with higher as well as with equal priority threads To create a thread, you extend java.lang.Thread or implement java.lang.Runnable

Unit 156 Example 1: Extending java.lang.Thread 1 class OurClass1{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass1Tester{ 8 public static void main(String args[]){ 9 OurClass1 oc = new OurClass1(); 10 oc.run(); 11 run(); 12 } 13 static void run(){ 14 for(int i=0; i<100; i++) 15 System.out.print("Shabab."); 16 } 17 } 1 class OurClass2 extends Thread{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass2Tester{ 8 public static void main(String args[]){ 9 OurClass2 oc = new OurClass2(); 10 oc.start(); 11 run(); 12 } 13 static void run(){ 14 for(int i=0; i<100; i++) 15 System.out.print("Shabab."); 16 } 17 }

Unit 157 Example 2: Implementing java.lang.Runnable 1 class OurClass3 implements Runnable{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass3Tester{ 8 public static void main(String args[]){ 9 OurClass3 oc = new OurClass3(); 10 Thread th = new Thread(oc); 11 th.start(); 12 run(); 13 } 14 static void run(){ 15 for(int i=0; i<100; i++) 16 System.out.print("Shabab."); 17 } 18 }

Unit 158 Example 3: Creating Multiple Threads 1 public class SleepingThread extends Thread { 2 private int countDown = 5; 3 private static int threadCount = 0; 4 private int threadNumber = ++threadCount; 5 public SleepingThread() { 6 System.out.println("Making " + getName()); 7 } 8 public void run() { 9 while(true) { 10 try { // don’t wake a sleeping thread before its sleep time expires! 11 System.out.println(getName() + " Executing."); 12 sleep((long)(Math.random()*5000)); 13 }catch(InterruptedException ie){ 14 System.out.println(getName() + " Interrupted."); 15 } 16 if(--countDown == 0) return; 17 } } 18 public static void main(String[] args) { 19 for(int i = 0; i < 5; i++) 20 new SleepingThread().start(); 21 System.out.println("All Threads Started"); 22 }}

Unit 159 Threads: Pictorial View of a Lifetime. Thread created new ready running finished blocked start() run() yield(), or time expired stop(), or complete stop() suspend(), sleep(), or wait() stop() resume(), notify(), or notifyAll()

Unit 1510 Example 4: A Timer Thread 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TimerThread extends JFrame implements Runnable{ 5 private JTextField jtf = new JTextField(10); 6 private JButton jb = new JButton("Start/Stop"); 7 private int counter = 0; 8 private boolean startStop = true; 9 TimerThread(){ 10 Container cp = getContentPane(); 11 cp.setLayout(new FlowLayout()); 12 cp.add(jtf); 13 cp.add(jb); 14 setSize(200,200); 15 setTitle("A Timer Thread"); 16 show(); 17 jb.addActionListener(new ActionListener(){ 18 public void actionPerformed(ActionEvent ae){ 19 startStop = !startStop; 20 } });}

Unit 1511 Example 4: A Timer Thread (cont’d) 21 public void run(){ 22 while (true){ 23 try{ 24 Thread.sleep(1000); 25 }catch(Exception e){} 26 if (startStop) 27 jtf.setText(Integer.toString(counter++)); 28 } 29 } 30 public static void main(String args[]){ 31 new Thread(new TimerThread()).start(); 32 } 33 }

Unit 1512 Example 5: A Visitor Thread 1 import java.util.*; 2 public class VisitorThread extends Thread { 3 private Object []array; 4 public VisitorThread(Object array[]) { 5 this.array = array; 6 } 7 public void run() { 8 Integer temp; 9 this.setName("The Visitor"); 10 for(int i = 0; i < array.length; i++){ 11 temp = (Integer)array[i]; 12 array[i] = new Integer (temp.intValue() + i); 13 if(i%3 == 0) Thread.yield(); 14 } 15 System.out.println(getName() + " done!"); 16 } 17 }

Unit 1513 Example 5: A Sorter Thread 1 import java.util.*; 2 public class SorterThread extends Thread { 3 private Object []array; 4 public SorterThread(Object array[]){ 5 this.array = array; 6 } 7 public void run() { 8 int minPos = 0; Object temp; 9 for(int i = 0; i < array.length - 1; i++){ 10 minPos = i; 11 if(i%3 == 0) Thread.yield(); 12 for(int k = i + 1; k < array.length; k++){ 13 if(((Integer)array[k]).compareTo(array[minPos]) < 0) 14 minPos = k; 15 } 16 temp = array[minPos]; 17 array[minPos] = array[i]; 18 array[i] = temp; 19 } 20 System.out.println(getName() + " done!"); 21 } 22 }

Unit 1514 Example 5: A Tester Thread 1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); 9 new TesterThread(100); 10 for(int i = 0; i < array.length; i++){ 11 array[i] = new Integer(r.nextInt(100)); 12 } 13 SorterThread sorter = new SorterThread(array); 14 VisitorThread visitor = new VisitorThread(array); 15 sorter.start(); 16 visitor.start(); 17 for(int i = 0; i < array.length; i++){ 18 System.out.println(array[i]); 19 } 20 System.out.println(Thread.currentThread().getName() + " done!"); 21 } 22 }

Unit 1515 Threads Priorities As wehave seen, the run( ) methods of the threads in a program will be executed “simultaneously” The programmer can influence the order of threads executions using threads’ priorities Every Java thread has a priority in the range Thread.MIN_PRIORITY (a constant value, 1) and Thread.MAX_PRIORITY (a constant value, 10). The default priority is Thread.NORMAL_PRIORITY (a constant value, 5) Each new thread inherits the priority of the thread that creates it 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 for it

Unit 1516 Example 6: Prioritizing the Visitor Thread 1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); new TesterThread(100); 9 for(int i = 0; i < array.length; i++){ 10 array[i] = new Integer(r.nextInt(100)); 11 } 12 SorterThread sorter = new SorterThread(array); 13 VisitorThread visitor = new VisitorThread(array); 14 sorter.start(); visitor.start(); 15 visitor.setPriority(Thread.MAX_PRIORITY); 16 Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 17 for(int i = 0; i < array.length; i++){ 18 System.out.println(array[i]); 19 } 20 System.out.println(Thread.currentThread().getName() + " done!"); 21 } 22 }