java多线程编程制作电子时钟
模拟一个电子时钟,它可以在任何时候被启动或者停止,并可以独立的运行。
1.定义一个Clock类。它继承Label类,并实现Runnable接口。这个类中有一个Thread类型的clocker域,以及start()和run()方法。在run()方法中,每隔一秒就把系统时间显示为label的文本。
classClockextendsLabelimplementsRunnable
{
//定义Thread类型的clocker域
publicThreadclocker=null;
publicClock()
{
//初始化时,把label设置为当前系统时间
//调用toString方法转化为String类型
setText(newDate().toString());
}
//控制线程的启动
publicvoidstart()
{
if(clocker==null)
{
//clocker通过Thread类构造方法得到的对象进行初始化,并将Clock类的当前对象作为参数
clocker=newThread(this);
clocker.start();
}
}
//控制线程的停止
publicvoidstop()
{
clocker=null;
}
//实现Runnable接口中的run()方法
publicvoidrun()
{
ThreadcurrentThread=Thread.currentThread();
//判断clocker是否是当前运行的线程
while(clocker==currentThread)
{
setText(newDate().toString());
try
{//休眠1s钟
clocker.sleep(1000);
}
catch(InterruptedExceptionie)
{
System.out.println("Threaderror:"+ie);
}
}
}
}
2.定义一个ClockFrame类。它继承Frame类,并实现ActionListener接口。在这个类中定义start和stop按钮来控制电子时钟的运行。并且这个类有一个Clock类的域,把这个Clock类对象添加到ClockFrame类中显示。
publicclassClockFrameextendsFrameimplementsActionListener
{
privateButtonstart=newButton("Start");
privateButtonstop=newButton("Stop");
privateClockc=newClock();
publicClockFrame()
{
super("电子时钟");
//设置窗体使用流式布局
setLayout(newFlowLayout());
//添加按钮并且为其注册监听器
add(start);
start.addActionListener(this);
add(stop);
stop.addActionListener(this);
//使用继承WindowAdapter的匿名内部类来实现窗口的关闭
addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEventwe)
{System.exit(0);}
});
add(c);
//使构件在窗口中得到合理的安排。
pack();
setVisible(true);
}
//通过调用Clock对象中的方法,实现对事件的响应。
publicvoidactionPerformed(ActionEventae)
{
if(ae.getSource()==start)
{
c.start();
}
else
if(ae.getSource()==stop)
c.stop();
}
publicstaticvoidmain(String[]args)
{
newClockFrame();
}
}
3、运行:
注:
需要导入的类:
importjava.awt.*; importjava.awt.event.*; importjava.util.Date;
再给大家一个网友的做法,非常不错
importjava.awt.*;
importjavax.swing.*;
importjava.util.Date;
/*TimeDemo.java
*@src
publicclassTimeDemoextendsJFrameimplementsRunnable{
Threadclock;
publicstaticvoidmain(String[]args){
TimeDemotd=newTimeDemo();
td.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//点击可见窗口右上角的红叉关闭
}
publicTimeDemo(){
super("雪地漫步---java多线程数字时钟");//继承父类构造方法,这里相当于Font("雪地漫步---java多线程数字时钟");
setTitle("kk");//这个则是子类的
this.setFont(newFont("TimesNewRoman",Font.BOLD,60));//设置字体大小
this.go();//自定义go方法,用于以后开启线程
setBounds(400,300,300,100);
this.setVisible(true);
}
publicvoidgo(){
stop();
if(clock==null){
//线程执行的主题作为Thread类构造方法的参数。
clock=newThread(this);
clock.start();//开启线程,实现run方法
}
}
publicvoidrun(){
while(true)//让线程一直进行
{
//repain()方法是来控制Graphics类的paint()方法的,repain()方法执行一次,即让paint()方法执行一次
repaint();
try{
Thread.sleep(1000);//参数是毫秒,1秒即1000毫秒
}catch(InterruptedExceptione){}
}
}
publicvoidstop(){
clock=null;
}
publicvoidpaint(Graphicsg){
Strings="";
Datenow=newDate();
inthour=now.getHours();
intminute=now.getMinutes();
intsecond=now.getSeconds();
s=hour+":"+minute+":"+second;
g.setColor(Color.green);
Dimensiondim=getSize();
g.fillRect(0,0,dim.width,dim.height);
g.setColor(Color.red);
g.drawString(s,20,80);
}
}
例子三:思路更加的巧妙,分享给大家
importjava.awt.BorderLayout;
importjava.awt.Canvas;
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.sql.Date;
importjava.text.SimpleDateFormat;
importjava.util.Calendar;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
classClockextendsCanvasimplementsRunnable{
/*
http://ohgrateboy.blog.163.com我的博客
*/
privatestaticfinallongserialVersionUID=3660124045489727166L;
Threadt;
JFrameframe=newJFrame();
JPanelconPane;
Stringtime;
inti=0;
Datetimer;
publicClock(){
conPane=(JPanel)frame.getContentPane();
conPane.setLayout(newBorderLayout());
conPane.setSize(280,40);
conPane.setBackground(Color.white);
conPane.add(this,BorderLayout.CENTER);
t=newThread(this);//实例化线
t.start();//调用线程
frame.setVisible(true);
frame.setSize(300,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicvoidrun(){
while(true){
try{
Thread.sleep(1000);//休眠1秒钟
}catch(InterruptedExceptione){
System.out.println("异常");
}
this.repaint(100);
}
}
publicvoidpaint(Graphicsg){
Fontf=newFont("宋体",Font.BOLD,16);
SimpleDateFormatSDF=newSimpleDateFormat("yyyy'年'MM'月'dd'日'HH:mm:ss");//格式化时间显示类型
Calendarnow=Calendar.getInstance();
time=SDF.format(now.getTime());//得到当前日期和时间
g.setFont(f);
g.setColor(Color.orange);
g.drawString(time,45,25);
}
publicstaticvoidmain(Stringargs[]){
newClock();
}
}