
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

// vier Threads, diesmal mit Aufruf start
// 10 * 1,2,3,4  addieren= Summe 100
public class Thread07 extends JFrame {

  JButton BnStart = new JButton("Start");
  JLabel label;

  //Frame konstruieren
  public Thread07() {
    setSize(500, 320);
    setLocation(100,10);
    setTitle("Thread06");

    label = new JLabel();
    label.setFont( new Font("Arial", Font.BOLD,32));
    label.setText( "0" );

    this.getContentPane().add(label, BorderLayout.CENTER);


    JPanel pn = new JPanel();
    pn.setLayout( new FlowLayout() );

    pn.add(BnStart);
    this.getContentPane().add(pn, BorderLayout.SOUTH);
    BnStart.setFont( new Font("Arial", Font.BOLD,32));

    BnStart.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        BnStart_Click();
      }
    });

    setVisible(true);
  }

  private void  BnStart_Click() {
     long summe;
    myThread[] f;

      // Erzeugen des Synchroniserungs-Objekt
      // nur damit wird das Label verändert
    CalcLabel calc ;
    calc = new CalcLabel(label);

    f = new myThread[10];
    for (int i=0; i<f.length; i++) {
      f[i]=new myThread(1, calc);
    }

    summe = 0;
    label.setText( "0" );
    for (int i=0; i<f.length; i++) {
      f[i].start();
    }

  } // Start



  //Überschreiben, damit das Programm bei Herunterfahren des Systems beendet werden kann
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if(e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }


  public static void main(String[] args) {
    Thread07 frame = new Thread07();
    frame.setVisible(true);
  }


}


// Erzeugen des Synchroniserungs-Objekt
// nur mit Hilfe dieser Klasse wird das Label verändert
class CalcLabel {
  JLabel myLabel;

  public CalcLabel(JLabel label) {
    myLabel=label;
  }
    // synchronized
   public  void add(long nr) {
      System.out.println("in add");
      String s = myLabel.getText();
      long summe = Long.valueOf(s).longValue();
      summe = summe + nr;
      myLabel.setText( Long.toString(summe)  );
  }

} // CalcLabel



class myThread extends Thread {

  long nummer=0;
  CalcLabel _calc;

  public myThread (long nr, CalcLabel calc) {
     _calc = calc;
     nummer = nr;
  }


  public void run() {
    int time;
    long summe=0;
    for (int i=0; i<10; i++) {
      summe+=nummer;
      //System.out.println(nummer);
      time = (int) (Math.random()*30);
      try {
        Thread.sleep(time);
      }
      catch (InterruptedException e) {
      }
    } // for
    _calc.add(summe);
    
  }



}


