Java Programming
Week 4

Dr. Ernest J. Friedman-Hill

ejfried@herzberg.ca.sandia.gov

http://herzberg.ca.sandia.gov/JavaCourse

 

What We're Doing Today

Homework

 

import java.awt.*;

import java.awt.event.*;

 

class Planet {

private String m_name;

private double m_gravity;

 

Planet(String s, double g)

{m_name = s; m_gravity = g;}

final public String name(

{return m_name;}

final public double gravity(

{return m_gravity;}

}

 

 

public class Projectile

extends WindowAdapter

implements ItemListener, ActionListener {

 

// Widgets

private Choice m_planetChoice, m_angleChoice;

private TextField m_velocityField;

private TextArea m_outputArea;

private Button m_goButton;

 

// Static data

private static Planet m_planetList[] =

{ new Planet("Mercury", 9.8*0.378),

new Planet("Venus", 9.8*0.905),

new Planet("Earth", 9.8),

new Planet("Mars", 9.8*0.379),

new Planet("Jupiter", 9.8*2.529),

new Planet("Saturn", 9.8*1.066),

new Planet("Uranus", 9.8*0.903),

new Planet("Neptune", 9.8*1.096),

new Planet("Pluto", 9.8*0.069)};

// State

private Planet m_planet = m_planetList[2];

private double m_velocity = 10.0;

private int m_angle = 45;

 

public Projectile() {

Frame f

= new Frame("Projectile Calculator");

f.addWindowListener(this);

Panel p = new Panel();

// Choice for which planet

m_planetChoice = new Choice();

for (int i=0; i<m_planetList.length; i++)

m_planetChoice.addItem(

m_planetList[i].name());

m_planetChoice.select(m_planet.name());

m_planetChoice.addItemListener(this);

p.add(new Label("Planet: "));

p.add(m_planetChoice);

 

// Choice for which planet

m_angleChoice = new Choice();

for (int i=0; i<=90; i+=5)

m_angleChoice.addItem(

Integer.toString(i));

m_angleChoice.select(

Integer.toString(m_angle));

m_angleChoice.addItemListener(this);

p.add(new Label("Launch Angle (deg): "));

p.add(m_angleChoice);

 

 

m_velocityField = new TextField(10);

m_velocityField.setText(

Double.toString(m_velocity));

m_velocityField.addActionListener(this);

p.add(new Label(

"Launch Velocity (m/s): "));

p.add(m_velocityField);

 

// Button for "Go"

m_goButton = new Button("Calculate");

m_goButton.addActionListener(this);

p.add(m_goButton);

 

// Window for output

m_outputArea = new TextArea(10,40);

 

// Put Frame together

f.add("South", p);

f.add("Center", m_outputArea);

f.pack();

f.show();

}

 

public static void main(String[] argv) {

Projectile p = new Projectile();

}

 

public void windowClosing(WindowEvent e) {

System.exit(0);

}

 

 

 

 

private boolean validVelocity() {

try {

m_velocity =

Double.valueOf(m_velocityField.

getText()).doubleValue();

return true;

}

catch (NumberFormatException nfe) {

m_velocityField.setText(

Double.toString(m_velocity));

return false;

}

}

 

public void actionPerformed(ActionEvent ae) {

if (validVelocity() &&

ae.getSource() == m_goButton)

calculate();

}

 

public void itemStateChanged(ItemEvent ie) {

if (ie.getStateChange()==ItemEvent.SELECTED)

if (ie.getItemSelectable()==m_planetChoice)

m_planet = m_planetList[m_planetChoice.

getSelectedIndex()];

else if

(ie.getItemSelectable()==m_angleChoice)

m_angle =

5 * m_angleChoice.getSelectedIndex();

}

 

 

 

private void calculate() {

final double TWOPI = 2.0 * Math.PI;

double v_v = m_velocity *

Math.sin(m_angle/360.0 * TWOPI);

double v_h = m_velocity *

Math.cos(m_angle/360.0 * TWOPI);

double maxHeightTime =

v_v / m_planet.gravity();

double distance =

v_h * 2.0 * maxHeightTime;

 

maxHeightTime =

((int) (maxHeightTime * 100.0)) / 100.0;

distance =

((int) (distance * 100.0)) / 100.0;

 

m_outputArea.append("With an initial" +

" velocity of " + m_velocity +

" m/s at an angle of " +

m_angle + " degrees from" +

" horizontal,\n");

m_outputArea.append("a projectile on " +

m_planet.name() +

" will travel " + distance +

" meters. The trip will take " +

(2.0 * maxHeightTime) +

" seconds.\n");

}

Projectile Calculator

Java Threads

Threads Example

1) Create a Thread object

 

2) Call Thread.start()

Thread Example

public class Crawdad extends Thread {

private String m_name;

private int m_steps = 10;

public Crawdad(String name)

{ m_name = name; }

public void run() {

while (true) {

try {

Thread.sleep(

(long)(Math.random() * 1000));

if (m_steps-- == 0) {

System.out.println(m_name+" done!");

break;

}

} catch (InterruptedException ie){}

}

}

}

Thread Example

public class Race {

public static void main(String [] a) {

Crawdad bob = new Crawdad("Bob");

Crawdad fred = new Crawdad("Fred");

bob.start();

fred.start();

System.out.println("They're off!");

}

}

c:\> java Race

They're off!

Fred done!

Bob done!

c:\> java Race

They're off!

Bob done!

Fred done!

The sleep() Method

public static void sleep(long t) throws InterruptedException;

 

public void interrupt();

 

public boolean interrupted();

Stopping a Thread

 

 

private m_running = true;

public void stop() {m_running = false;}

public void run() {

while (m_running) {

// Do something interesting...

}

}

 

ExThread t = new ExThread();

t.start();

...

t.stop();

 

Thread Synchronization

Thread Synchronization

float

withdraw(float amt)

{

if (m_balance >= amt)

return (m_balance -= amt);

else

return m_balance;

}

 

Thread 1

Thread 2

myacct.withdraw(amt);

myacct.withdraw(amt);

if (m_balance >= amt)

if (m_balance >= amt)

return (m_balance -= amt);

return (m_balance -= amt);

 

Thread Synchronization

synchronized float

withdraw(float amt)

{

if (m_balance >= amt)

return (m_balance -= amt);

else

return m_balance;

}

 

Thread 1

Thread 2

myacct.withdraw(amt);

myacct.withdraw(amt);

 

if (m_balance >= amt)

return (m_balance -= amt);

if (m_balance >= amt)

return m_balance;

 

Thread Synchronization

Thread Synchronization

class Foo

{

synchronized void a() {}

synchronized void b() {}

synchronized void c() {}

}

 

class Bar

{

void doSomething(Foo f)

{

synchronized (f) {

f.a(); f.b(): f.c();

}

}

}

Waiting for Something

Waiting for Something

public class Printer extends Thread {

private InputBuffer m_ib;

private boolean m_running = true;

public Printer(InputBuffer ib)

{ m_ib = ib; setDaemon(true); }

public void run()

{

while(m_running)

{

char c = (char) m_ib.get();

System.out.write(c);

}

}

}

 

Waiting for Something

public class Main {

static char [] s_string =

"Some Text\n".toCharArray();

 

public static void

main(String argv[]) {

InputBuffer ib =

new InputBuffer();

Printer p = new Printer(ib);

// This will print the chars

p.start();

 

for (int i=0; i<10; i++)

for (int j=0;

j<s_string.length;

j++)

ib.put(s_string[j]);

}

}

 

Waiting for Something

public class InputBuffer {

 

final int MAX = 20;

private char m_buffer[] =

new char[MAX];

private int m_nchars = 0;

 

 

public synchronized void put(char c) {

while (m_nchars == MAX)

try { wait(100); }

catch (InterruptedException ie) {}

 

m_buffer[m_nchars++] = c;

notify();

}

 

public synchronized int get() {

while (m_nchars == 0)

try { wait(100); }

catch (InterruptedException ie)

{return -1;}

 

notify();

return m_buffer[--m_nchars];

}

}

Waiting for Something

c:/users/root/tmp> java Main

 

Stxet emoS

oS

emtxet emotxet emoS etext

oSmoS

xet emtxet emoS

emoS

txet txet emoS

c:/users/root/tmp> java Main

 

Stxet emoS

oS

emtxet emotxet emoS emtext

moSoS

txe

moSt etxet emoS

txet emoS

txet emoS

 

c:/users/root/tmp> java Main

 

Stxet emoS

oS

emtxet emotxet emoS emoS

txet emoS

S

motxet emoS

emoS

S

Waiting for Something

Thread Scheduling

Java I/O

File Streams

"Wrapping" Streams

// FOS can write bytes to a file

FileOutputStream fos = new FileOutputStream("tempfile");

 

// PrintWriter can render basic types as

// text, translate text to bytes

PrintWriter pw = new PrintWriter(fos);

Character I/O

Writing Custom Streams

 

TextArea ta = new TextArea(10,40);

PrintWriter pw =

new PrintWriter(new TextAreaWriter(ta),

true);

 

// Print using PrintWriter methods;

// text appears in TextArea!

pw.print(123.456);

pw.println(" is the answer");

 

public class TextAreaWriter extends Writer

{

private StringBuffer m_str;

private TextArea m_ta;

public TextAreaWriter(TextArea area)

{

m_str = new StringBuffer(100);

m_ta = area;

}

public void close() throws IOException

{

flush();

}

public void flush() throws IOException

{

m_ta.append(m_str.toString());

m_str.setLength(0);

}

public void write(int c) throws IOException

{

m_str.append((char) c);

}

public void write(char c[])

throws IOException

{

m_str.append(c);

}

public void write(char c[],

int offset, int len)

throws IOException

{

m_str.append(c, offset, len);

}

}

Final Assignment

Final Assignment

a collection of Reader or Writer subclasses that transform text: one that turns all letters to uppercase, one to lower case, one that corrects common spelling errors...

Final Assignment

Final Assignment