欢迎来到天天文库
浏览记录
ID:8975731
大小:34.50 KB
页数:4页
时间:2018-04-13
《java--多线程实现计数器》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、java--多线程实现计数器同时开始5个线程,用各自的文本框显示count,和按钮控制count的自加importjava.awt.*;importjava.awt.event.*;importjava.applet.*; classTickerextendsThread{ privateButtont=newButton("toggle"); privateTextFieldtf=newTextField(10); //开关控制count的变化 privaterunFlag=true; privateintcou
2、nt=0; classStopimplementsActionListener{ @Override publicvoidactionPerformed(ActionEvente){ runFlag=!runFlag; } } publicTicker(Containerc){ t.addActionListener(newStop()); //Panel容器 Panelp=newPanel(); p.add(t); p.add(tf); c.add(p
3、); } @Override publicvoidrun(){ while(true){ try( Thread.currentThread().sleep(200); }catch(InterruptedExceptione){ e.printStackTrace(); } if(runFlag) tf.setText(Integer.toString(++count)); } }} publicclassCounte
4、rextendsApplet{ privateButtonstart=newButton("Start"); privatebooleanstarted=false; privateintsize=0; privateTicker[]ts; @Override publicvoidinit(){ start.addActionListener(newStart()); add(start); ts=newTicker[size]; for(inti=0;i5、 ts[i]=newTicker(Counter.this); } } classStartimplementsActionListener{ @Override publicvoidactionPerformed(ActionEvente){ if(!started){ started=true; for(inti=0;i6、ticvoidmain(String[]args){ Counterc=newCounter(); Frameframe=newFrame("程序片"); frame.addWindowListener( newWindowAdapter(){ @Override publicvoidwindowClosing(WindowEvente){ System.exit(0); } } ); frame.setSize(37、00,c.size*50); frame.add(c,BorderLayout.CENTER); c.init(); c.start(); frame.setVisible(true); }}
5、 ts[i]=newTicker(Counter.this); } } classStartimplementsActionListener{ @Override publicvoidactionPerformed(ActionEvente){ if(!started){ started=true; for(inti=0;i6、ticvoidmain(String[]args){ Counterc=newCounter(); Frameframe=newFrame("程序片"); frame.addWindowListener( newWindowAdapter(){ @Override publicvoidwindowClosing(WindowEvente){ System.exit(0); } } ); frame.setSize(37、00,c.size*50); frame.add(c,BorderLayout.CENTER); c.init(); c.start(); frame.setVisible(true); }}
6、ticvoidmain(String[]args){ Counterc=newCounter(); Frameframe=newFrame("程序片"); frame.addWindowListener( newWindowAdapter(){ @Override publicvoidwindowClosing(WindowEvente){ System.exit(0); } } ); frame.setSize(3
7、00,c.size*50); frame.add(c,BorderLayout.CENTER); c.init(); c.start(); frame.setVisible(true); }}
此文档下载收益归作者所有