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

public class Thread08 extends JFrame {

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

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

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

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

    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    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() {
    double summe, a, b, diff;     
    myThread [] mT = new myThread[4];

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

    a=0.0;
    diff = (10.0-0.0)/mT.length;
    b=0.0;
    for (int i=0; i<mT.length; i++) {
      b+=diff;
      mT[i] = new myThread(i+1,a,b, calc);
      a+=diff;
    }
    summe = 0;
    label.setText( "0" );

    for (int i=0; i<mT.length; i++) {
      mT[i].start();
    }
	try {
     for (int i=0; i<mT.length; i++) {
      mT[i].join();
     }
    }
    catch (InterruptedException e) {
    }
    label.setText( ""+calc.getSumme() );

  } // Start




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


}


// Erzeugen des Synchroniserungs-Objekt
// nur mit Hilfe dieser Klasse wird das Label verändert
class Calc {
  private double summe=0;

  public Calc() {
  }
    // synchronized
   public synchronized void add(double summe) {
      this.summe+=summe;
  }

  public double getSumme() {
    return summe;
  }

} // Calc



class myThread extends Thread {

  long _nr=0;
  double _a, _b;
  Calc _calc;

  public myThread (long nr, double a, double b, Calc calc) {
    System.out.println("a: "+a+"  b:"+b);
     _calc = calc;
     _a =a;
     _b = b;
     _nr = nr;
  }


  public void run() {
    int time;
    double summe=0.0;
    int n=1000000000;
    n=10000000;
    double h = (_b-_a)/n;
    double x, y, xe;
    x=_a;
    for (int i=0; i<n; i++) {
      // System.out.println("id :"+_nr+"   x:"+x);
      y= 2.0*x-3.0;
//      summe+=y*h;
      _calc.add(y*h);      
      x+=h;
    } // for
    //System.out.println("id :"+summe);

  
    
  }



}


