Lösung Übung 19: Beispiel für Multithreading
import java.awt.*;
import java.awt.event.*;
public class ThreadApplikation extends Frame {
ThreadApplikation myself;
TextArea tArea;
Button startButton;
Button stoppButton;
MyThread t1;
MyThread t2;
MyThread t3;
public ThreadApplikation() {
myself = this;
setLayout( new FlowLayout() );
tArea = new TextArea( 25,20 );
startButton = new Button("Start");
startButton.addActionListener( new StartListener() );
stoppButton = new Button("Stopp");
stoppButton.addActionListener( new StoppListener() );
add( tArea );
add( startButton );
add( stoppButton );
this.addWindowListener(
new WindowAdapter() {
// Bei Programmexit-Event beende Programm
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(600,400);
this.setVisible( true );
}
public void printText( String str ){
tArea.append( str );
}
public static void main( String[] args ) {
new ThreadApplikation();
}
class StartListener implements ActionListener {
public void actionPerformed( ActionEvent e ) {
t1 = new MyThread( myself, "Thread 1");
t2 = new MyThread( myself, "Thread 2");
t3 = new MyThread( myself, "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
class StoppListener implements ActionListener {
public void actionPerformed( ActionEvent e ) {
try {
t1.interrupt();
t2.interrupt();
t3.interrupt();
t1 = null;
t2 = null;
t3 = null;
}
catch( SecurityException ex ){
System.exit(1);
}
}
}
}
class MyThread extends Thread {
private String myName;
private int counter;
private ThreadApplikation p;
public MyThread( ThreadApplikation parent, String name ) {
p = parent;
myName = name;
counter = 0;
}
public void run() {
while( !interrupted() ) {
counter++;
String str = myName + ": " + counter + "\n";
p.printText( str );
}
}
}
[Index]