Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Threads (1)
Threads are “mini-programs” that only exist inside the context of a bigger
program. Taking a program running as a representation of a process, a thread
would be a sub-process, which shares the same resources allocated to that
process, and cannot live on its own.
However threads have their own execution stack and program counter, to name
a few…
P
T1
T2
T3
T4
When running threads, you get the impression that they are all being executed
“concurrently”, although in reality they normally comply to a round-robin
mechanism, where a time slice is allocated.
COMPSCI230S1C – Models Client programming
© Emilia Mendes
1
TwoThreadsTest.java
Creates two Thread objects: One displays “GREEN”, the other displays “RED”
Thread “green”
0 GREEN
1 GREEN
2 GREEN
3 GREEN
4 GREEN
5 GREEN
6 GREEN
7 GREEN
8 GREEN
9 GREEN
DONE! GREEN
Thread “red”
0 RED
1 RED
2 RED
3 RED
4 RED
5 RED
6 RED
7 RED
8 RED
9 RED
DONE! RED
Ideal Scenario:
COMPSCI230S1C – Models Client programming
© Emilia Mendes
2
TwoThreadsTest.java
But what really happens given sleep((int)(Math.random() * 1000)); is!
COMPSCI230S1C – Models Client programming
© Emilia Mendes
3
class TwoThreadsTest {
public static void main (String args[]) {
new SimpleThread("GREEN").start();
new SimpleThread("RED").start();
}
}
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
}
catch (InterruptedException e) {
}
}
System.out.println("DONE! " + getName());
}
}
Try four threads!!!
COMPSCI230S1C – Models Client programming
© Emilia Mendes
4
COMPSCI230S1C – Models Client programming
© Emilia Mendes
5
Threads and Interface Design
Here is an example of a red ball that bounces 1,000 times.
The first time you press “Start”, the ball starts to bounce.
If you immediately after that press the button “Close” it continues
bouncing as if you haven’t done anything….
You can only interact with the program when the ball has finished
bouncing!!!
Would you like to use an interface like that??????
COMPSCI230S1C – Models Client programming
© Emilia Mendes
6
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
// Shows an animated bouncing ball.
public class BounceNoThreads {
public static void main(String[] args) {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class BounceFrame extends JFrame {
private BallCanvas canvas;
public static final int WIDTH = 250;
public static final int HEIGHT = 200;
public BounceFrame() {
setSize(WIDTH, HEIGHT);
setTitle("Bounce With No Threads");
Container contentPane = getContentPane();
canvas = new BallCanvas();
contentPane.add(canvas, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
Method called
when you press
the button “Start”
addButton(buttonPanel, "Start",
new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
addBall(Color.red);
}
});
COMPSCI230S1C – Models Client programming
© Emilia Mendes
7
addButton(buttonPanel, "Close",
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
contentPane.add(buttonPanel, BorderLayout.NORTH);
}
// Adds a button to a container c is the container object, title is the
// button title, listener is the action listener for the button
public void addButton(Container c, String title, ActionListener listener){
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
// Adds a bouncing ball to the canvas and makes it bounce 1,000 times.
public void addBall(Color color) {
try {
Ball b = new Ball(canvas, color);
canvas.add(b);
for (int i = 1; i <= 1000; i++) {
b.move();
Thread.sleep(5); //doesn’t create a new thread!!!!
}
}
catch (InterruptedException exception) {
}
}
}
Repeats this loop 1000
times, without giving a
chance to be interrupted
COMPSCI230S1C – Models Client programming
© Emilia Mendes
8
// The canvas that draws the balls.
class BallCanvas extends JPanel {
// Adds a ball to the canvas. Param b the ball to add
public void add(Ball b) {
balls.add(b);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i < balls.size(); i++)
{
Ball b = (Ball)balls.get(i);
b.draw(g2);
}
}
private ArrayList balls = new ArrayList();
}
………..
COMPSCI230S1C – Models Client programming
© Emilia Mendes
9
Threaded Bouncing Ball
What is the difference here?
Each ball is created and associated with a thread that moves it 1,000
times, each time sleeping for 5 milliseconds.
This way, when one thread sleeps, it gives an opportunity to other
threads to execute, thus sharing resources…..
COMPSCI230S1C – Models Client programming
© Emilia Mendes 10
Threaded Bouncing Ball
Differences from previous code
Creates a new object ball,
Adds it to the Jpanel,
Creates a new thread and
associates it with the ball
object
Starts the thread
public void addBall(Color color) {
Ball b = new Ball(canvas, color);
canvas.add(b);
BallThread thread = new BallThread(b);
thread.start();
}
class BallThread extends Thread {
private Ball b;
// creates a new thread that will bounce the ball aBall
public BallThread(Ball aBall) {
b = aBall;
}
A Thousand times, the thread object
public void run() {
moves the ball once and then goes to
try {
sleep for five milliseconds.
for (int i = 1; i <= 1000; i++) {
By doing so, it gives an opportunity
b.move();
for another thread to take control.
sleep(5);
}
}
catch (InterruptedException exception) {
}
}
COMPSCI230S1C – Models Client programming
© Emilia Mendes 11
Threaded Bouncing Ball – source code
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class BounceThreads {
public static void main(String[] args) {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class BounceFrame extends JFrame {
private BallCanvas canvas;
public static final int WIDTH = 250;
public static final int HEIGHT = 200;
public BounceFrame() {
setSize(WIDTH, HEIGHT);
setTitle("Bounce With Threads");
Container contentPane = getContentPane();
canvas = new BallCanvas();
contentPane.add(canvas, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
COMPSCI230S1C – Models Client programming
© Emilia Mendes 12
addButton(buttonPanel, "Start", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
addBall(Color.red);
}
});
addButton(buttonPanel, "Close", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
contentPane.add(buttonPanel, BorderLayout.NORTH);
}
// Adds a button to a container.
// param c is the container object
// param title is the button title
// param listener is the action listener for the button
public void addButton(Container c, String title, ActionListener listener) {
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
// Adds a bouncing ball to the canvas and starts a thread.
public void addBall(Color color) {
Ball b = new Ball(canvas, color);
canvas.add(b);
BallThread thread = new BallThread(b);
thread.start();
}
}
COMPSCI230S1C – Models Client programming
© Emilia Mendes 13
class BallThread extends Thread {
private Ball b;
// creates a new thread that will bounce the ball aBall
public BallThread(Ball aBall) {
b = aBall;
}
public void run() {
try {
for (int i = 1; i <= 1000; i++) {
b.move();
sleep(5);
}
}
catch (InterruptedException exception) {
}
}
}
// The canvas that draws the balls.
class BallCanvas extends JPanel {
// Add a ball to the canvas. Param b the ball to add
public void add(Ball b) {
balls.add(b);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i < balls.size(); i++) {
Ball b = (Ball)balls.get(i);
b.draw(g2);
COMPSCI230S1C – Models Client programming
© Emilia Mendes 14
}
}
private ArrayList balls = new ArrayList();
}
// A ball that moves and bounces off the edges of a component
class Ball {
private Component canvas;
private Color color;
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private int x = 0;
private int y = 0;
private int dx = 2;
private int dy = 2;
// Constructs a ball in the upper left corner
// c the component in which the ball bounces
public Ball(Component c, Color col) {
canvas = c;
color = col;
}
// Draws the ball at its current position. Param g2 the graphics context
public void draw(Graphics2D g2) {
g2.setColor(color);
g2.fill(new Ellipse2D.Double(x, y, XSIZE, YSIZE));
}
// Moves the ball to the next position, reversing direction
// if it hits one of the edges
public void move() {
COMPSCI230S1C – Models Client programming
© Emilia Mendes 15
x += dx;
y += dy;
if (x < 0) {
x = 0;
dx = -dx;
}
if (x + XSIZE >= canvas.getWidth()) {
x = canvas.getWidth() - XSIZE;
dx = -dx;
}
if (y < 0) {
y = 0;
dy = -dy;
}
if (y + YSIZE >= canvas.getHeight()) {
y = canvas.getHeight() - YSIZE;
dy = -dy;
}
canvas.paint(canvas.getGraphics());
}
}
COMPSCI230S1C – Models Client programming
© Emilia Mendes 16
Exercise: Change the code for BounceThreads.java by adding another
button which starts BLUE balls, each associated with a thread.
What are the two small modifications you have to make?
COMPSCI230S1C – Models Client programming
© Emilia Mendes 17
ANSWER:
addButton(buttonPanel, "Start Red Ball", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
addBall(Color.red);
}
});
addButton(buttonPanel, "Start Blue Ball", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
addBall(Color.blue);
}
});
And what does need to change to add a green ball?
COMPSCI230S1C – Models Client programming
© Emilia Mendes 18