Unit 161 Further Threads Programming Some Terminologies on Multithreading Example 1: Threads Synchronization Example 2: ‘Salaam Shabab’ Animation Example.

Slides:



Advertisements
Similar presentations
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Advertisements

Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
CS4273: Distributed System Technologies and Programming I Lecture 4: Java Threads and Multithread Programming.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.
(c) 2006 E.S.Boese All Rights Reserved. Threads and Timers Chapter 19 - Student.
13-Jun-15 Animation. 2 Moving pictures Animation—making objects that appear to move on the screen—is done by displaying a series of still pictures, one.
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.
Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
24-Jun-15 Simple Animation. 2 The bouncing ball The “bouncing ball” is to animation what “Hello world” is to programming With a single Thread, we can.
Unit 071 Review of Applets Learning Outcomes oDistinguish between Java Applications and Java Applets. oWrite applet programs that can load images and play.
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.
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.
Java: Animation Chris North cs3724: HCI. Animation? Changing graphics over time Examples: cartoons Clippy, agents/assistants Hour glass Save dohicky Progress.
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.
Introducing Graphics There are generally two types of graphics facilities in Java –Drawing –GUIs We concentrate on drawing here We will draw on a Graphics.
(c) 2008 E.S.Boese All Rights Reserved. Threads and Media Chapter 8 - Lecture Slides 1.
Applets CS 3331 Sections 3.3 & 4.7 of [Jia03].
Internet Software Development Applets Paul J Krause.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Lesson 36: The calculator – Java Applets. 1. Creating Your First Applet HelloWorldApp is an example of a Java application, a standalone program. Now you.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
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.
(c)2009 by E.S. Boese. All Rights Reserved. Classes Chapter 13 – Lecture Slides 1 Got class?
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Review of Graphics in Java,
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds.
CompSci Event Handling. CompSci Event Handling The Plan  Sequential (Single Thread) Model  Event Model  Making the GUI interactive  Examples.
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.
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 –
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Ch15 簡單計算機 物件導向系統實務. Ch22_Main.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch22_Main { public static void main(String.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Multithreading and Garbage Collection Session 16.
Lesson 28: More on the GUI button, frame and actions.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
Multithreaded applets
Chapter 13: Multithreading
Graphical User Interfaces -- GUIs
Object-Orientated Analysis, Design and Programming
Animation 12-Sep-18.
Animation 6-Nov-18.
Threads II IS
Animation 15-Nov-18.
Animation 18-Nov-18.
Drawing in Java.
Java Threads (Outline)
Java Threads (Outline)
Animation 25-Feb-19.
Chapter 15 Multithreading
Threads and Multithreading
Computer Science 209 Images and GUIs.
9. Threads SE2811 Software Component Design
Presentation transcript:

Unit 161 Further Threads Programming Some Terminologies on Multithreading Example 1: Threads Synchronization Example 2: ‘Salaam Shabab’ Animation Example 3: Car Race Animation Example 4: Rocket Launching Animation

Unit 162 Some Terminologies on Multithreading Thread scheduling: arranging the threads to be executed in an order that they may take CPU control Timeslice: The length of time for which a thread runs and this time may depend on the thread's priority or its use of resources such as memory and I/O Preemption: to interrupt and suspend (“swap out”) the currently executing thread in order to start or continue running ("swap in") another thread Synchronization: The process of ensuring that that a shared resource is used by only one of the many contending threads at any moment Deadlock: A situation where two or more threads are unable to proceed because each is waiting for one of the others to do something Starvation: indefinite postponement of the execution of lower-priority threads by higher-priority ones

Unit 163 Threads Synchronization When a block of Java code guarded by the synchronized keyword, it can be executed by only one thread at any time A shared resource (implemented by a given code segment) may be corrupted if it is accessed simultaneously by multiple threads. –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 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

Unit 164 Example 1: Threads Synchronization 1 class BanckAccount{ 2 private int balance; 3 public BanckAccount(int balance){ 4 this.balance = balance; 5 } 6 void doNothing(){ 7 depositWithdraw(10); 8 depositWithdraw(20); 9 depositWithdraw(30); 10 } 11 void depositWithdraw(int money){ 12 try { 13 balance += money; 14 Thread.sleep((long)(Math.random()*1000)); 15 balance -= money; 16 } catch(Exception e){} 17 } 18 int get(){ 19 return balance; 20 } 21 }

Unit 165 Example 1: Threads Synchronization (cont’d) 22 public class UnsafeBankAccount extends Thread{ 23 BanckAccount ba; 24 public static void main( String[] args ){ 25 BanckAccount ba = new 26 BanckAccount(0); 27 for(int i=0; i<9; i++) 28 new UnsafeBankAccount(ba).start(); 29 } 30 public UnsafeBankAccount(BanckAccount ba){ 31 this.ba = ba; 32 } 33 public void run(){ 34 doWork(); 35 } 36 public void doWork(){ 37 System.out.println(getName()+" got balance: "+ba.get()); 38 ba.doNothing(); 39 System.out.println(getName()+" got balance: "+ba.get()); 40 } 41 } Make depositWithdraw() and get() synchronized to solve this problem

Unit 166 Example 2: ‘Salaam Shabab’ Animation 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class AnimationPanel extends JPanel implements Runnable { 5 private Font myFont; 6 private int increment = 1; 7 public int xSize, ySize, yCoord = 0; 8 int delay; 9 Thread animator; 10 private boolean onOff=true; 11 public AnimationPanel(int delay) { 12 xSize=400; 13 ySize=350; 14 setSize(xSize, ySize); 15 myFont = new Font ("Serif", Font.ITALIC, 30); 16 animator = new Thread(this); 17 animator.start(); 18 } 19 public void setOnOff(boolean onOff) { 20 this.onOff = onOff; 21 }

Unit 167 Example 2: ‘Shabab’ Animation (cont’d) 22 public void paintComponent(Graphics g) { 23 super.paintComponent(g); 24 g.setColor(Color.yellow); 25 g.fillRect(0,0,xSize, ySize); 26 g.setColor (Color.red); 27 g.setFont(myFont); 28 if(onOff) { 29 g.drawString ("Salaam ", xSize/2-100, ySize/2 + yCoord); 30 g.drawString ("Shabab!", xSize/2, ySize/2 - yCoord); 31 } 32 } 33 public void run () { 34 while(true){ 35 yCoord = yCoord + increment;//yCoord min is -150 and max if((yCoord == (ySize-50)/2 || (yCoord == -(ySize-50)/2))) 37 increment = -increment; // increment by -1 now 38 try{ 39 Thread.sleep(delay); 40 } catch(InterruptedException e){} 41 repaint(); 42 } 43 } 44 }

Unit 168 Example 2: ‘Shabab’ Animation (cont’d) 45 public class SalamShababAnimation extends JApplet{ 46 private Button myButton; 47 private boolean onOffButton = true; 48 private AnimationPanel ap; 49 public void init() { //validate parsing the parameter "fps" 50 int delay = Integer.parseInt(getParameter("fps")); 51 delay = (delay<10)? 10 : delay; 52 Container cp = getContentPane(); 53 cp.setLayout(new BorderLayout()); 54 ap = new AnimationPanel(delay); 55 myButton = new Button ("Start/Stop"); 56 myButton.addActionListener(new ActionListener(){ 57 public void actionPerformed(ActionEvent ae){ 58 onOffButton = !onOffButton; 59 ap.setOnOff(onOffButton); 60 }}); 61 cp.add(myButton,BorderLayout.NORTH); 62 cp.add(ap, BorderLayout.CENTER); 63 } 64 }

Unit 169 Example 3: Car Race Animation 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import java.util.*; 5 class DrivingPanel extends JPanel implements Runnable { 6 private int delay; 7 private Thread animator; 8 private Image car; 9 static final int WIDTH = 600; 10 static final int HEIGHT = 200; 11 private int xPosition, speed; 12 private Random random; 13 public DrivingPanel(Image car, int delay) { 14 this.car = car; 15 this.delay = delay; 16 setSize(WIDTH,HEIGHT); 17 xPosition = getWidth(); 18 random = new Random(); 19 speed = random.nextInt(5);//+1; 20 animator = new Thread(this); 21 animator.start(); 22 }

Unit 1610 Example 3: Car Race Animation (cont’d) 23 public void run() { 24 while (true) { 25 repaint(); 26 speed = random.nextInt(5)+1; 27 xPosition -= speed; 28 if (xPosition < -car.getWidth(this)) 29 xPosition = getWidth(); 30 try { 31 Thread.sleep(delay); 32 } catch (InterruptedException e) { 33 break; 34 } 35 } 36 } 37 public void paintComponent(Graphics g) { 38 super.paintComponent(g); 39 g.setColor(Color.white); 40 g.fillRect(0, 0, getWidth(), getHeight()); 41 g.drawImage(car, xPosition, getHeight()/2, this); 42 } 43 }

Unit 1611 Example 3: Car Race Animation (cont’d) 44 public class CarRaceAnimation extends JApplet { 45 public void init() { // You should validate parsing the parameter! 46 int delay = Integer.parseInt(getParameter("fps")); 47 delay = (delay<10)? 10: delay; 48 Image car = getImage(getCodeBase(),"car.gif"); 49 DrivingPanel lane1 = new DrivingPanel(car, delay); 50 DrivingPanel lane2 = new DrivingPanel(car, delay); 51 Container cp = getContentPane(); 52 cp.setLayout(new GridLayout(2,1)); 53 cp.add(lane1); 54 cp.add(lane2); 55 } 56 } Download the car image used in the example from here. here You can also obtain the rocket image for the next example.rocket image

Unit 1612 Example 4: Rocket Launcher 1 import java.applet.*; 2 import java.awt.*; 3 import java.awt.event.*; 4 import javax.swing.*; 5 public class RocketLauncher extends JApplet implements Runnable, ActionListener { 6 private Image rocket; 7 private int x, y, sec=10; 8 private Thread myThread; 9 private Timer timer = new Timer(1000,this); 10 JTextField tf = new JTextField(5); 11 JButton b = new JButton("Start Count Down"); 12 public void init() { 13 rocket = Toolkit.getDefaultToolkit().getImage("rocket.jpg"); 14 x = 50; 15 y = getSize().height-rocket.getHeight(this)-380; 16 myThread = new Thread(this); 17 tf.setText(" "+sec+" "); 18 b.addActionListener(this); 19 }

Unit 1613 Example 4: Rocket Launcher (cont’d) 20 public void actionPerformed( ActionEvent ae) { 21 if(ae.getSource() == b) 22 timer.start(); 23 if(ae.getSource() == timer) 24 if(--sec>0) 25 tf.setText(" "+sec+" "); 26 else{ 27 timer.stop(); 28 myThread.start(); 29 } 30 } 31 public void run() { 32 while (y-- != -rocket.getHeight(this)) { 33 try { 34 myThread.sleep(10); 35 } catch (InterruptedException e) {} 36 repaint(); 37 } 38 } 39 public void update(Graphics g){ 40 paint(g); 41 }

Unit 1614 Example 4: Rocket Launcher (cont’d) 42 public void paint(Graphics g) { 43 g.drawImage(rocket,x,y,null); 44 } 45 public static void main(String [] args){ 46 JFrame frame = new JFrame("My Rocket Launch Pad"); 47 frame.setSize(400,750); 48 Container cp = frame.getContentPane(); 49 cp.setLayout(new GridLayout(1,2)); 50 JPanel p = new JPanel(); 51 JPanel p1 = new JPanel(); 52 p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS)); 53 RocketLauncher applet = new RocketLauncher(); 54 p.add(applet.b); 55 p1.add(applet.tf); 56 p.add(p1); 57 cp.add(p); 58 applet.setBackground(Color.white); 59 cp.add(applet); 60 frame.setVisible(true); 61 applet.init(); 62 } 63 }

Unit 1615 Exercises 1.Modify Example 2 so that when the animation is stopped, the strings Salaam and Shabab remain displayed on the animation screen. 2.Improve the car race animation by 1.Adding a button to control when to start the next race 2.Incorporating up to four cars in the race 3.Displaying the winning car after every race 4.Incorporating different car models 3.Modify each of the preceding examples so that each of them can work as an applet as well as a standalone application.