Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.

Slides:



Advertisements
Similar presentations
Web Design & Development Lecture 19. Java Graphics 2.
Advertisements

Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
Multithreading Why multi-threads Defining and creating threads An example with two threads Life cycle of a thread An example with user interface Problem.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Threads Part II.
Public class MyThread1 extends Thread { public void start() { } public void run() { System.out.print(“Hello \n”) } public class MyThread2 extends Thread.
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.
1 Recitation 11. Applet Applets. An applet is a Java program that is started by a browser (e.g. netscape or internet explorer) when an html file has a.
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 161 Further Threads Programming Some Terminologies on Multithreading Example 1: Threads Synchronization Example 2: ‘Salaam Shabab’ Animation Example.
Unit 071 Review of Applets Learning Outcomes oDistinguish between Java Applications and Java Applets. oWrite applet programs that can load images and play.
Slides prepared by Rose Williams, Binghamton University ICS201 Lectures 18 : Threads King Fahd University of Petroleum & Minerals College of Computer Science.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI 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.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
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.
Internet Software Development Applets Paul J Krause.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
CS12420 – Swing and threads Lynda Thomas
Lesson 36: The calculator – Java Applets. 1. Creating Your First Applet HelloWorldApp is an example of a Java application, a standalone program. Now you.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
tiled Map Case Study: Rendering with JPanel © Allan C. Milne v
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
CSTP FS99CS423 (cotter)1 Java Graphics java.awt.*;
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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
(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,
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
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.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
Practical Session 10: Animation. Animation kinds There are three basic kinds of animation: 1. Moving object 2. Changing pictures 3. Combination of 1 and.
1 Applications & Applets Standalone applications & Java applets Peter Mozelius DSV/UCSC.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
Ch15 簡單計算機 物件導向系統實務. Ch22_Main.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch22_Main { public static void main(String.
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה. בשבוע שעבר  paint  Graphics  repaint.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
GUI Programming in Java Hao Jiang Boston College April, 2009.
Multithreaded applets
Graphical User Interfaces -- GUIs
Animation 12-Sep-18.
Chapter 19 Java Never Ends
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
Animation 6-Nov-18.
Animation 15-Nov-18.
Animation 18-Nov-18.
Drawing in Java.
Animation 25-Feb-19.
Computer Science 209 Images and GUIs.
CiS 260: App Dev I Chapter 6: GUI and OOD.
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
Animation 17-Sep-19.
Presentation transcript:

Java Threads Part II

Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications in Java

The Runnable Interface Another way to create a thread is to have a class implement the Runnable interface  The Runnable interface has one method heading: public void run(); A class that implements Runnable must still be run from an instance of Thread  This is usually done by passing the Runnable object as an argument to the thread constructor

The Runnable Interface: An Outline public class ClassToRun extends SomeClass implements Runnable {... public void run() { // Fill this as if ClassToRun // were derived from Thread }... public void startThread() { Thread theThread = new Thread(this); theThread.run(); }... }

The Runnable Interface: An Example

The Runnable Interface: An Example (Cont’d)

1.import javax.swing.*; 2.public class TimeThread extends JFrame implements Runnable { private JTextField sec, min, hrs; 5. private JPanel panel; 6. private int time = 0; public TimeThread() { 9. super(“Time"); sec = new JTextField(3); sec.setEditable(false); //makes textfield uneditable 12. min = new JTextField(3); min.setEditable(false); 13. hrs = new JTextField(3); hrs.setEditable(false); panel = new JPanel(); panel.add(hrs); panel.add(min); panel.add(sec); getContentPane().add(panel); pack(); setVisible(true); 20. } Example 1

1. public void run() 2. { 3. try { 4. while(true) { 5. Thread.sleep(1000); time++; 6. sec.setText(time%60 + ""); //Display seconds 7. min.setText((time – (time/3600)*3600)/60 + ""); //Display minutes 8. hrs.setText(time/ ""); //Display hours 9. } 10. } catch(InterruptedException e) {} 11. } 12. public static void main(String[] args) 13. { 14. TimeThread t = new TimeThread(); 15. Thread mytime = new Thread(t); 16. mytime.start(); 17. } 18.} Example 1- Continued

Threads For Animation 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.

Example 2 – Thread Animations import java.awt.*; import javax.swing.*; public class UpDown extends JFrame { public UpDown () { setSize(400,500); add(new DrawingArea()); } class DrawingArea extends JPanel implements Runnable { int radius, xc, yc; Thread t; public DrawingArea() { radius = 20; xc = 30; //signifies x location yc = 20; //signifies y location Thread t = new Thread (this); t.start(); }

public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.fillOval(xc - radius, yc - radius, 2*radius, 2*radius); } public void run(){ int incry=10; int sleepFor = 50; while(true) { yc += incry ; repaint(); if(yc - radius getSize().height) incry = -incry; //reflect the ball back try{ Thread.sleep (sleepFor); }catch(InterruptedException e) {} } // end while } } public static void main(String[] args){ new UpDown().setVisible(true); }} Example 2 – continued

Example 3: ‘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. }

Example 3: ‘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. }

Example 3: ‘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.}

Example 4: 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. }

Example 4: 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.}

Example 4: 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

Example 5: 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. }

Example 5: 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. }

Example 5: 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.}