You are on page 1of 16

Chapter 7: Threads

1. Create an applet that displays the time in 3 different countries.


import java.awt.*;
import java.applet.*;
import java.util.*;

public class WorldTime extends Applet implements Runnable


{
private Date toDay = new Date();
private Thread th = null;
private boolean goOn = true;

public void start()


{
if(th==null)
{
th = new Thread(this);
th.start();
}
}

public void run()


{
while(goOn)
{
toDay = new Date();
repaint();
try
{
Thread.sleep(1000);
}
catch(Exception e) {}
}
}

public void paint(Graphics g)


{
g.drawString("Tel-Aviv : " + toDay,50,100);
toDay.setTime(toDay.getTime()-7*3600*1000);
g.drawString("New-York : " + toDay,50,150);
toDay.setTime(toDay.getTime()-4*3600*1000);
g.drawString("Vancouver : " + toDay,50,200);
}

public void stop()


{
if(th!=null)
{
goOn=false;
th = null;
}
}
}
2. Create an applet that presents 10 different balls with different colors moving like
billiard balls and changing their dimension all the time in order to give the filling that
they move in space.

import java.awt.*;
import java.util.*;
import java.applet.*;

class Ball implements Comparable

protected int radius;

private Color color;

private Dimension dimension;

private Point position;

private Point startingPoint;

Ball(int radiusVal, Color colorVal, Dimension dimensionVal, Point startingPointVal)


{

radius = radiusVal;

color = colorVal;

dimension = dimensionVal;

position = startingPointVal;

startingPoint = startingPointVal;

public int getRadius()

{
//This method returns the ball radius

//complete the missing code

return radius;
}

public Color getColor()

//This method returns the ball raidus

//complete the missing code

return color;

}
public Dimension getDimension()

//This method returns the dimension of the ball

//complete the missing code

return dimension;

public Point getPosition()

//This method returns the ball position. Please notice

//that there is a class named Point in the java.awt package.

//complete the missing code

return position;

public int compareTo(Object other)


{
return radius - ((Ball)other).radius;
}

interface PositionChangeable
{
int STEP_X = 20;
int STEP_Y = 10;

int SLEEP_TIME = 100;

void move();
}

class CrazyBall extends Ball implements PositionChangeable


{

int factorX=1, factorY=1;

CrazyBall(int radiusVal, Color colorVal, Dimension dimensionVal, Point


startingPointVal)

super(radiusVal, colorVal, dimensionVal, startingPointVal);

public void move()

//add the missing code so each invocation of the method move

//will move the ball in its dimension like a ball in billiard.

//This method should change the position of the ball

int x = (int)(getPosition().getX());

int y = (int)(getPosition().getY());

int width = (int)(getDimension().width);


int height = (int)(getDimension().height);

Dimension dim = getDimension();

int rad = getRadius();

if((x>(width-rad-STEP_X) && factorX==1) || (x<STEP_X && factorX==-1 ) )

//complete your code here

factorX = factorX * (-1);

if((y>(height-rad-STEP_Y) && factorY==1) || (y<STEP_Y && factorY==-1) )

//complete your code here

factorY = factorY * (-1);

getPosition().translate(STEP_X*factorX, STEP_Y*factorY);

}
void paint(Graphics g)
{
g.setColor(getColor());

g.fillOval((int)(getPosition().getX()),
(int)(getPosition().getY()),getRadius(),getRadius());

}
}
interface SizeChangeable
{
public abstract void changeSize();
}
interface SizeAndPositionChangeable extends SizeChangeable, PositionChangeable
{
}

class CrazySizeBall extends CrazyBall implements SizeAndPositionChangeable


{
private int sizeFactor = 2;
private int minRadius;
private int maxRadius;

CrazySizeBall(int radiusVal, Color colorVal, Dimension dimensionVal, Point


startingPointVal)
{
super(radiusVal, colorVal, dimensionVal, startingPointVal);
minRadius = radiusVal/2;
maxRadius = radiusVal*2;
}

public void changeSize()


{
if(radius<minRadius || radius>maxRadius)
{
sizeFactor *=-1;
}
radius += sizeFactor;
}
}
public class CrazySizeApplet extends Applet implements Runnable
{
private SizeAndPositionChangeable vec[];
private Thread thread;
private boolean goOn = true;
public void init()
{
vec = new SizeAndPositionChangeable[5];
Color colors[] = {Color.red, Color.yellow, Color.blue, Color.green, Color.orange};
Point startingPoints[];
Dimension dim = new Dimension(getWidth(), getHeight());
for(int index=0; index<vec.length; index++)
{
vec[index] = new CrazySizeBall( (int)(10+40*Math.random()),
colors[index],
dim,
new Point((int)((dim.width-40)*Math.random()),
(int)((dim.height-40)*Math.random())) );
}
}
public void start()
{
if(thread==null)
{
thread = new Thread(this);
thread.start();
}

}
public void paint(Graphics g)
{
Arrays.sort(vec);
for(int m=0; m<vec.length; m++)
{
((CrazyBall)vec[m]).paint(g);
}
}
public void run()
{
while(goOn)
{
for(int index=0; index<vec.length; index++)
{
vec[index].move();
vec[index].changeSize();
}

repaint();
try
{
Thread.sleep(Moveable.SLEEP_TIME);
}
catch(Exception e) {}
}
}
public void stop()
{
goOn=false;
thread=null;
}
}

3. Create an applet that displays an image of winter in Europe (snow…) and draws
little pieces of falling snow in order to give the filling of falling snow.
4. Create an applet that displays a ball that moves like a billiard ball within a
rectangle. The size of the ball and the dimension of the rectangle should be sent as
parameters from the HTML document. The applet should present the user two buttons:
“PAUSE” and “CONTINUE”. Pressing the “PAUSE” button should pause the ball
moving. Pressing the “CONTINUE” should cause the ball continue its moving. You
should use the methods wait() and notify().

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class PauseContinueBall extends Applet


implements Runnable, ActionListener
{
private Button pauseBt,continueBt;
private int stepX=1, stepY=1;
private Point position;
private int ballRadius;
private Dimension dim;
private Thread thread;
private boolean goOn = true;
private int threadStatus;
private final int WAIT = 1;
private final int CONTINUE = 2;

public void actionPerformed(ActionEvent event)


{
if(event.getActionCommand().equals("pause"))
{
//pausing the ball moving
System.out.println(Thread.currentThread().getName());
threadStatus = WAIT;
}
else
{
//continue the ball moving
System.out.println(Thread.currentThread().getName());
threadStatus = CONTINUE;
synchronized(this)
{
this.notify();
}
}
}

public void init()


{
int width,height;
pauseBt = new Button("pause");
continueBt = new Button("continue");
add(pauseBt);
add(continueBt);
pauseBt.addActionListener(this);
continueBt.addActionListener(this);
String ballRadiusStr = getParameter("radius");
String heightStr = getParameter("height");
String widthStr = getParameter("width");

int defaultWidth, defaultHeight;


defaultWidth = getSize().width;
defaultHeight = getSize().height;

if(ballRadiusStr!=null)
{
try
{
ballRadius = Integer.parseInt(ballRadiusStr);
}
catch(NumberFormatException e)
{
e.printStackTrace();
ballRadius = 10;
}
}
else
{
ballRadius = 10;
}

if(widthStr!=null)
{
try
{
width = Integer.parseInt(widthStr);
}
catch(NumberFormatException e)
{
e.printStackTrace();
width = defaultWidth;
}
}
else
{
width = defaultWidth;
}

if(heightStr!=null)
{
try
{
height = Integer.parseInt(heightStr);
}
catch(NumberFormatException e)
{
e.printStackTrace();
height = defaultHeight;
}
}
else
{
height = defaultHeight;
}

dim = new Dimension(width,height);


position = new Point(ballRadius*2,ballRadius*2);

public void start()


{
if(thread==null)
{
thread = new Thread(this);
thread.start();
}
}

public void paint(Graphics g)


{
g.fillOval(position.x,position.y,2*ballRadius,2*ballRadius);
}

public void stop()


{
stopThread();
thread = null;
}

public void stopThread()


{
goOn = false;
}

public void run()


{
while(goOn)
{
if(threadStatus==WAIT)
{
synchronized(this)
{
try
{
this.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

//changing the ball location


if(position.x>dim.width-ballRadius*2 && stepX>0 || position.x<stepX &&
stepX<0)
{
stepX = stepX*(-1);
}
if(position.y>dim.height-ballRadius*2 && stepY>0 || position.y<stepY &&
stepY<0)
{
stepY = stepY*(-1);
}
position.translate(stepX,stepY);

//calling repaint
repaint();

try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}

The HTML document is:

<APPLET CODE=PauseContinueBall WIDTH=500 HEIGHT=400>


<PARAM NAME=width VALUE=400>
<PARAM NAME=height VALUE=300>
<PARAM NAME=radius VALUE=12>
</APPLET>
5. Create an applet that displays balls that move like a billiard balls within a
rectangle. The number of balls should be sent as parameters from the HTML document.
The applet should display a pair of “PAUSE” and “CONTINUE” buttons for each one
of the balls. Pressing the “PAUSE” button should pause the ball moving. Pressing the
“CONTINUE” should make the ball continue its moving. You should use the methods
wait() and notify(). Please note that you should create a separate thread for each one of
the balls.
6. Create an applet that presents a gambling machine. In order to make the applet
authentic use an image of a real gambling machine. The gambling machine should
have three little windows in which the user can see changing images (of different
fruits) when he pulls the hand (by pressing the relevant button). The speed of the
changing images in each one of the little windows should be authentic: The changing
speed in the left window should become slower before the changing speed in the
center window which its speed should become slower before the changing speed in the
right window. As you can figure out, the changing images in the left window stops
before the changing images in the center window, which stops before the changing
images in the right window. If all of the images are equal when the machine stops then
the user wins. The respond should be the appropriate sound for wining.

You might also like