Download presentation
Presentation is loading. Please wait.
1
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
2
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
3
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
4
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 }
5
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
6
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 }
7
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 150 36 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 }
8
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 }
9
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 }
10
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 }
11
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
12
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 }
13
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 }
14
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 }
15
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.