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

import java.util.*;

// Berechnet Primzahlen, Ausgabe der einzelnen Primzahlen
public class Thread09a extends JFrame {

  JButton BnStart = new JButton("Start");
  JTextArea editor;

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

    editor = new JTextArea();
    editor.setFont( new Font("Arial", Font.BOLD,32));
    this.getContentPane().add(new JScrollPane( editor), 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();
      }
    });

    setLocation(400,30);
    setVisible(true);
  }

  private void  BnStart_Click() {
    myThread [] mT = new myThread[4];

    PaketStation calc ;
    calc = new PaketStation(100000);

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

    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) {
    }
    for (int i=0; i<mT.length; i++) {
      String s = mT[i].getErg();
      editor.append(s+"\n");
    }

  } // Start




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


}


// Erzeugen des Synchroniserungs-Objekt
// nur mit Hilfe dieser Klasse wird das Label verändert
class PaketStation {
  private int n;
  private int number;

  public PaketStation(int n) {
    this.n = n;
    number=2;
  }
    // synchronized
   public synchronized int getNumber() {
      number++;
      if (number<=n)
        return number;
      else
        return 0;
  }


} // PaketStation



class myThread extends Thread {

  private PaketStation _calc;
  private int _nr;
  private ArrayList _liste = new ArrayList();
 
  public myThread (int nr, PaketStation calc) {
     _nr = nr;
    System.out.println("nr: "+_nr);
     _calc = calc;
  }

 public String getErg() {
    String s="";
    for (int i=0; i<_liste.size(); i++) {
      s+="Id: "+_nr+"   "+((Integer) _liste.get(i)).toString()+"\n";
    }
    return s;
  }

  public void run() {
    int number;
    int rest;
    boolean bOk;
    number = _calc.getNumber();
    while (number!=0) {
      bOk=true;
      for (int i=2; i<number; i++) {
        rest = number % i;
        if (rest==0) {
          bOk=false;
          break;
        }
      }
      if (bOk) {
        _liste.add( new Integer(number) );
      }
      number = _calc.getNumber();
    } // for
  }  // run



}


