java多线程编程制作电子时钟

 更新时间:2015年11月20日 08:51:50   投稿:hebedich  
本文给大家汇总了几个使用java多线程编程实现的电子时钟的代码,思路非常的巧妙,也都很实用,有需要的小伙伴可以参考下。

  模拟一个电子时钟,它可以在任何时候被启动或者停止,并可以独立的运行。

1.定义一个Clock类。它继承Label类,并实现Runnable接口。这个类中有一个Thread类型的clocker域,以及start()和run()方法。在run()方法中,每隔一秒就把系统时间显示为label的文本。

class Clock extends Label implements Runnable
{
  //定义Thread类型的clocker域
  public Thread clocker=null;
  public Clock()
  {
    
    //初始化时,把label设置为当前系统时间
    //调用toString方法转化为String类型
    setText(new Date().toString());
  }
  //控制线程的启动
  public void start()
  {
    if(clocker==null)
    {
      //clocker通过Thread类构造方法得到的对象进行初始化,并将Clock类的当前对象作为参数
      clocker=new Thread(this);
      clocker.start();
    }

  }
  //控制线程的停止
  public void stop()
  {
    clocker=null;
  }
  //实现Runnable接口中的run()方法
  public void run()
  {
    Thread currentThread=Thread.currentThread();
    //判断clocker是否是当前运行的线程
    while(clocker==currentThread)
    {
            setText(new Date().toString());
            try
           {   //休眠1s钟
               clocker.sleep(1000);
      }
      catch (InterruptedException ie)
      {
        System.out.println("Thread error:"+ie);
      }
    }
  
  }

}

2.定义一个ClockFrame类。它继承Frame类,并实现ActionListener接口。在这个类中定义start和stop按钮来控制电子时钟的运行。并且这个类有一个Clock类的域,把这个Clock类对象添加到ClockFrame类中显示。

public class ClockFrame extends Frame implements ActionListener
{
  private Button start=new Button("Start");
  private Button stop=new Button("Stop");
  private Clock c=new Clock();
  public ClockFrame()
  {
    super("电子时钟");
    //设置窗体使用流式布局
    setLayout(new FlowLayout());
    //添加按钮并且为其注册监听器
    add(start);
    start.addActionListener(this);
    add(stop);
    stop.addActionListener(this);
    //使用继承WindowAdapter的匿名内部类来实现窗口的关闭
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent we)
      {System.exit(0);}
    });
    add(c);
    //使构件在窗口中得到合理的安排。
    pack();
    setVisible(true);


  }
  //通过调用Clock对象中的方法,实现对事件的响应。
  public void actionPerformed(ActionEvent ae)
  {
    if(ae.getSource()==start)
    {
      c.start();
    }
    else
      if(ae.getSource()==stop)
      c.stop();

  }
  public static void main(String[] args)
  {
    new ClockFrame();
  }
}

3、运行:

注:

需要导入的类:

import java.awt.*;
import java.awt.event.*;
import java.util.Date;

再给大家一个网友的做法,非常不错

import java.awt.*;  
import javax.swing.*;  
import java.util.Date;  
 
/*TimeDemo.java 
 * @src 
public class TimeDemo extends JFrame implements Runnable {  
 
  Thread clock;  
    
  public static void main(String[] args) {  
  TimeDemo td =new TimeDemo();  
  td.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //点击可见窗口右上角的红叉关闭  
   }  
    
  public TimeDemo(){  
   super("雪地漫步---java多线程数字时钟"); //继承父类构造方法,这里相当于Font("雪地漫步---java多线程数字时钟");  
setTitle("kk");  //这个则是子类的  
   this.setFont(new Font("Times New Roman",Font.BOLD,60));  //设置字体大小  
   this.go();    //自定义go方法,用于以后开启线程  
   setBounds(400,300,300,100);  
   this.setVisible(true);  
  }  
 
   public void go(){  
  stop();  
   if(clock==null){  
  //线程执行的主题作为Thread类构造方法的参数。  
   clock=new Thread(this);  
   clock.start();     //开启线程,实现run方法  
  }  
}  
 
  public void run() {  
    while(true)   //让线程一直进行  
  {  
//repain()方法是来控制Graphics类的paint()方法的,repain()方法执行一次,即让paint()方法执行一次  
      repaint();   
     try{  
      Thread.sleep(1000);   //参数是毫秒,1秒即1000毫秒  
     }catch(InterruptedException e){}  
    }  
   }  
 
  public void stop(){  
   clock=null;  
  }  
 
  public void paint(Graphics g){  
   String s="";  
   Date now=new Date();  
   int hour=now.getHours();                       
   int minute=now.getMinutes();  
   int second=now.getSeconds();  
   s=hour+":"+minute+":"+second;  
   g.setColor(Color.green);  
   Dimension dim=getSize();  
   g.fillRect(0, 0, dim.width, dim.height);  
   g.setColor(Color.red);  
   g.drawString(s, 20, 80);  
  }  
} 

例子三:思路更加的巧妙,分享给大家

import java.awt.BorderLayout;
 import java.awt.Canvas;
 import java.awt.Color;
 import java.awt.Font;
 import java.awt.Graphics;
 import java.sql.Date;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 class Clock extends Canvas implements Runnable{

   /*
   http://ohgrateboy.blog.163.com我的博客
   */

   private static final long serialVersionUID = 3660124045489727166L;
   Thread t;
   JFrame frame=new JFrame();
   JPanel conPane;
   String time;
   int i=0;
   Date timer;
   public Clock(){
     conPane=(JPanel)frame.getContentPane();
     conPane.setLayout(new BorderLayout());
     conPane.setSize(280,40);
     conPane.setBackground(Color.white);
     conPane.add(this,BorderLayout.CENTER);
     t=new Thread(this);        //实例化线
    t.start();    //调用线程
    
     frame.setVisible(true);
     frame.setSize(300, 150);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

   public void run(){

     while(true){

     try{

       Thread.sleep(1000);          //休眠1秒钟

    }catch(InterruptedException e){

       System.out.println("异常");
     }
     this.repaint(100);

   }

   }

   public void paint(Graphics g){

     Font f=new Font("宋体",Font.BOLD,16);

     SimpleDateFormat SDF=new SimpleDateFormat("yyyy'年'MM'月'dd'日'HH:mm:ss");//格式化时间显示类型
    Calendar now=Calendar.getInstance();

     time=SDF.format(now.getTime());    //得到当前日期和时间
    g.setFont(f);

     g.setColor(Color.orange);

     g.drawString(time,45,25);

   }
   public static void main(String args[]){
     new Clock();
   }

 } 

相关文章

  • elasticsearch head的安装及使用过程解析

    elasticsearch head的安装及使用过程解析

    这篇文章主要介绍了elasticsearch head的安装及使用过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • Spring MVC保证Controller并发安全的方法小结

    Spring MVC保证Controller并发安全的方法小结

    在 Spring MVC 中,默认情况下,@Controller 是单例的,这意味着所有请求共享一个 Controller 实例,为确保并发安全,Spring 并不会自动对 Controller 进行线程安全保护,本文给大家介绍了Spring MVC保证Controller并发安全的方法,需要的朋友可以参考下
    2024-11-11
  • Maven发布项目 (jar包) 到Nexus私服中的操作

    Maven发布项目 (jar包) 到Nexus私服中的操作

    这篇文章主要介绍了Maven发布项目 (jar包) 到Nexus私服中的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • Java Http请求传json数据乱码问题的解决

    Java Http请求传json数据乱码问题的解决

    这篇文章主要介绍了Java Http请求传json数据乱码问题的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Java防止短信盗刷和轰炸的解决方案

    Java防止短信盗刷和轰炸的解决方案

    短信盗刷和短信轰炸是项目开发中必须要解决的问题之一,它的优先级不亚于 SQL 注入的问题,今天我们就来看下,如何防止这个问题,需要的朋友可以参考下
    2024-02-02
  • Java8 Comparator: 列表排序的深入讲解

    Java8 Comparator: 列表排序的深入讲解

    这篇文章主要给大家介绍了关于Java 8 Comparator: 列表排序的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Java8具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-05-05
  • Spring Bean作用域与生命周期深入讲解

    Spring Bean作用域与生命周期深入讲解

    这篇文章主要介绍了浅谈Spring中Bean的作用域,生命周期和注解,从创建到消亡的完整过程,例如人从出生到死亡的整个过程就是一个生命周期。本文将通过示例为大家详细讲讲,感兴趣的可以学习一下
    2022-07-07
  • 轻松搞定SpringBoot JPA使用配置过程详解

    轻松搞定SpringBoot JPA使用配置过程详解

    Spring Boot是由Pivotal团队提供的全新框架,该框架使用了特定的方式来进行配置,它默认配置了很多框架的使用方式,就像 Maven整合了所有的Jar包,Spring Boot 整合了所有的框架
    2021-06-06
  • 深入理解Java设计模式之组合模式

    深入理解Java设计模式之组合模式

    这篇文章主要介绍了JAVA设计模式之组合模式的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下
    2021-11-11
  • Java实现操作excel表格

    Java实现操作excel表格

    在日常工作中,对Excel工作表格的操作处理可是多的数不清楚,下面是java语言对其的操作,有需要的小伙伴可以参考下
    2015-10-10

最新评论