java--多线程实现计数器

同时开始5个线程,用各自的文本框显示count,和按钮控制count的自加

java--多线程实现计数器

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

 

class Ticker extends Thread{

  private Button t=new Button("toggle");

  private TextField tf=new TextField(10);

  //开关控制count的变化

  private runFlag=true;

  private int count=0;

 

  class Stop implements ActionListener{

    @Override

    public void actionPerformed(ActionEvent e){

      runFlag=!runFlag;

    }

  }

  public Ticker(Container c){

    t.addActionListener(new Stop());

    //Panel容器

    Panel p=new Panel();

    p.add(t);

    p.add(tf);

    c.add(p); 

  }

 

  @Override

  public void run(){

    while(true){

      try(

        Thread.currentThread().sleep(200);

      }catch(InterruptedException e){

        e.printStackTrace();

      }

      if(runFlag)

        tf.setText(Integer.toString(++count));

    }

  }

}

 

public class Counter extends Applet{

 

  private Button start=new Button("Start");

  private boolean started=false;

  private int size=0;

  private Ticker[] ts;

  @Override

  public void init(){

    start.addActionListener(new Start());

    add(start);

    ts=new Ticker[size];

    for(int i=0;i<size;i++){

      ts[i]=new Ticker(Counter.this);

    }

  }

 

  class Start implements ActionListener{

    @Override

    public void actionPerformed(ActionEvent e){

      if(!started){

        started=true;

        for(int i=0;i<size;i++){

          ts[i].start();

        }

      }

    }

  }

 

  public static void main(String[] args){

    Counter c=new Counter();

    Frame frame=new Frame("程序片");

    frame.addWindowListener(

      new WindowAdapter(){

        @Override

        public void windowClosing(WindowEvent e){

          System.exit(0);

        }

      }

    );

    frame.setSize(300,c.size*50);

    frame.add(c,BorderLayout.CENTER);

    c.init();

    c.start();

    frame.setVisible(true);

  }

}

 

 

/**--注意--**/

以上代码都是在文本编辑器中写的,可能会有些许纰漏

 

你可能感兴趣的:(java)