Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises.

Slides:



Advertisements
Similar presentations
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Advertisements

Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
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.
Public class MyThread1 extends Thread { public void start() { } public void run() { System.out.print(“Hello \n”) } public class MyThread2 extends Thread.
CSE S. Tanimoto Java Threads 1 Java Threads (Outline) Motivation The class Thread Example program: ThreadRace The Runnable interface Example: Clock.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
Unit 161 Further Threads Programming Some Terminologies on Multithreading Example 1: Threads Synchronization Example 2: ‘Salaam Shabab’ Animation Example.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
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.
Threads Just Java: C10–pages 251- C11–pages 275-
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples.
Multithreading.
EE2E1. JAVA Programming Lecture 8 Multi-threading.
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
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.
1 Java Threads and Synchronization Review Modified from slides taken from
1 Java Threads Instructor: Mainak Chaudhuri
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
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.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
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.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Multithreading in JAVA
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Threading and Concurrency COM379T John Murray –
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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 and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
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 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
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.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Multithreading.
Multithreaded Programming in Java
Object-Orientated Analysis, Design and Programming
Chapter 19 Java Never Ends
Multithreading in Java
Advanced Programming in Java
Multithreading.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
9. Threads SE2811 Software Component Design
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises

Unit 152 Thread Priority Execution of multiple threads on a single CPU in some order is called scheduling. The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads. Thread priorities are integers ranging 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 runtime system chooses for execution the Runnable thread that has the highest priority. If two threads of the same priority are waiting for the CPU, the scheduler arbitrarily chooses one of them to run.

Unit 153 Thread Priority The values of constants in java.lang.Thread are as follows: The methods int getPriority() and setPriority(int priority) are used the accessor and mutator methods used for the priority of a Java thread. The default priority value of a thread is 5 (java.lang.NORM_PRIORITY) or it is the priority of the thread that constructed it. public static final intMAX_PRIORITY10 public static final intMIN_PRIORITY1 public static final intNORM_PRIORITY5

Unit 154 Thread Priority – Example 1 1.public class SimplePThread extends Thread { public SimplePThread(String str) { 4. super(str); //Thread can be created using a string 5. } 6. public void run() { 7. for (int i = 1; i < 400; i++) { 8. for(int j = 0; j < 40000; j++) 9. System.out.print(""); //Keeps thread busy 10. System.out.print(getName()); 11. } 12. System.out.print("."); 13. } 14. public static void main (String[] args) { Thread t1 = new SimplePThread("1"); 17. Thread t2 = new SimplePThread("2"); t1.setPriority(Thread.NORM_PRIORITY + 1); 20. t2.setPriority(Thread.NORM_PRIORITY - 1); System.out.println("Thread 1 has priority " + t1.getPriority()); 23. System.out.println("Thread 2 has priority " + t2.getPriority()); t1.start(); t2.start(); 26. } 27.}

Unit 155 The interrupt() method The interrupt() method (public void interrupt()) interrupts the current thread. If thread is inactive, an InterruptedException is thrown which must be caught. The isInterrupted() method (public boolean isInterrupted()) checks if the current thread is interrupted or not. An example shows their use.

Unit 156 Example 2 1.import javax.swing.*; 2.import java.awt.event.*; 3.public class TimeThread3 extends JFrame implements ActionListener { private JTextField sec, min, hrs; private JButton button; private JPanel panel; private TimerTh t; private int time = 0; public TimeThread3() 10. { 11. super("Time"); sec = new JTextField(3); sec.setEditable(false); 14. min = new JTextField(3); min.setEditable(false); 15. hrs = new JTextField(3); hrs.setEditable(false); button = new JButton("Stop"); button.addActionListener(this); panel = new JPanel(); panel.add(hrs); panel.add(min); panel.add(sec);panel.add(button); 20. getContentPane().add(panel); pack(); setVisible(true); t = new TimerTh(); t.start(); 23. }

Unit 157 Example 2 – Contd. 24. class TimerTh extends Thread //Inner Class 25. { public void run() 26. { try 27. { 27. while(true) 28. { Thread.sleep(1000); time++; 29. sec.setText(time%60 + ""); //Display seconds 30. min.setText((time - (time/3600)*3600)/60 + ""); //Display minutes 31. hrs.setText(time/ ""); //Display hours 32. } 33. } catch(InterruptedException e) { System.out.println("Timer Stops"); } 34. } 35. } Here the Thread appears as an Inner Class. Compare this with the example 2 of the previous lecture in which the thread was implemented by implementing the Runnable interface. As an Inner Class the thread can access the textfields hrs, min and sec of the enclosing class. Both usages are acceptable.

Unit 158 Example 2 – Contd. 36. public void actionPerformed(ActionEvent e) 37. { 38. t.interrupt(); //Stop the timer 39. if(t.isInterrupted()) //If successful, 40. { 41.JOptionPane.showMessageDialog(this, 42. "Time stopped " + hrs.getText() + ":" + min.getText() + ":" + sec.getText()); 42. System.exit(0); 43. } 44. } public static void main(String[] args) { new TimeThread3(); } 47. }

Unit 159 Thread Synchronization When two or more threads access a shared resource, (for example a variable), the resource may be corrupted e.g., unsynchronized threads accessing the same database Such blocks of code are usually called critical sections and must be executed in a mutually- exclusive way When a block of Java code guarded by the synchronized keyword, it can be executed by only one thread at any time You can synchronize an entire method or just a few lines of code by using the synchronized keyword Note that code that is thread-safe (i.e, guarded by synchronized ) is slower than code that is not. Next, we present an example which shows problems due to shared thread access and then the synchronized thread version.

Unit 1510 Example 2 class BankAccount { private int balance; public BankAccount(int balance) { this.balance = balance; } public void doNothing() { depositWithdraw(10); depositWithdraw(20); depositWithdraw(30); } public void depositWithdraw(int money) { try { balance += money; Thread.sleep((long)(Math.random()*1000)); balance -= money; } catch(InterruptedException e){} } int get() { return balance; } } public class UnsafeBankAccount extends Thread{ BankAccount ba; public UnsafeBankAccount(BankAccount ba) { this.ba = ba; } public void run() { System.out.println(getName()+" got balance: "+ba.get()); ba.doNothing(); System.out.println(getName()+" got balance: "+ba.get()); } public static void main(String[] args ){ BankAccount ba = new BankAccount(0); for(int i=0; i<9; i++) new UnsafeBankAccount(ba).start(); } }

Unit 1511 Thread Synchronization When the program is executed, it may produce erroneous output. This is because many threads are executing the method depositWithdraw(int money) and get() at the same time. So it may be possible that while one thread is incrementing the variable balance, many others are decreasing it and vice versa. In the output snapshot shown here, at one point the balance is 190 although practically the user deposits and withdraws a maximum amount of 30 each time.

Unit 1512 Thread Synchronization One solution to the problem pointed out is to use the synchronized keyword with all methods that deal with the variable balance. This is to ensure that only one thread accesses the variable balance at a time. Other threads may wait() while one thread is accessing and modifying the variable balance. The method wait() is inherited by the class java.lang.Thread from the class java.lang.Object. When the thread accessing and modifying the variable balance is done, it may notifyAll() threads waiting to execute the synchronized methods. The complete correct program appears on the next slide.

13 Example 3 class MyBankAccount { private int balance; private boolean busy = false; public MyBankAccount(int balance) {this.balance = balance; } public void doNothing() { depositWithdraw(10); depositWithdraw(20); depositWithdraw(30); } public synchronized void depositWithdraw(int money) { try { while(busy) wait(); busy = true; balance += money; Thread.sleep((long)(Math.random()*1000)); balance -= money; busy = false; notifyAll(); //notifies all waiting threads } catch(InterruptedException e){} } synchronized int get() { return balance; } synchronized boolean busy() {return busy; } } public class SafeBankAccount extends Thread{ MyBankAccount ba; public SafeBankAccount(MyBankAccount ba) { this.ba = ba; } public void run() { System.out.println(getName()+" got initial balance: "+ ba.get()); ba.doNothing(); System.out.println(getName()+" got final balance: "+ ba.get()); } public static void main(String[] args ){ MyBankAccount ba = new MyBankAccount(0); for(int i=0; i < 9; i++) new SafeBankAccount(ba).start(); }

Unit 1514 Threads Animation In addition to applications in accessing databases, threads can also be used to create animations. In the next example we show a program where a thread is used to create an animation of a ball moving vertically. The run() method increments the y coordinate of the ball to be drawn. If the y- coordinate exceeds the height of the window, the ball is reflected back by negating the increment. The complete program appears in the next slide.

15 Example 4 – Thread Animations import java.awt.*; import java.applet.Applet; public class UpDown extends Applet implements Runnable { int radius, x, y; Thread t; public void init() { radius = 20; x = 30; //signifies x location y = 20; //signifies y location Thread t = new Thread(this); t.start(); } public void paint(Graphics g) { g.setColor(Color.blue); g.fillOval(x - radius, y - radius, 2*radius, 2*radius); } public void run(){ int yDir = +1; int incr = 10; int sleepFor = 50; while(true) { y += (incr * yDir); repaint(); if(y - radius < incr || y + radius + incr > getSize().height) yDir *= -1; //reflect the ball back try{ t.sleep(sleepFor); }catch(InterruptedException e) {} } // end while }

Unit 1516 Exercises Q. 1 In the first example replace the statement for(int j = 0; j < 40000; j++) System.out.print(""); //Keeps thread busy with Thread.sleep(1000); Observe the output and explain why it happens. What happens to thread priorities? Q. 2 In Example 4, can the code to show the JOptionPane be included in the try … catch(InterruptedException e){ …. } clause? Is such uasge acceptable? Q. 3: In example 4, make the ball move in both horizontal and vertical directions.