黑马程序员技术交流社区
标题: Timer类内部调用线程之定时器+时钟Demo [打印本页]
作者: 尹丽峰 时间: 2013-4-26 23:06
标题: Timer类内部调用线程之定时器+时钟Demo
- package day0425;
- import java.awt.Color;
- import java.awt.FlowLayout;
- import java.util.Calendar;
- import java.util.TimerTask;
- import java.util.Timer;
- import javax.swing.JFrame;
- import javax.swing.JTextField;
- public class ThreadDemo2 extends JFrame
- {
- private static final long serialVersionUID = 1L;
- private JTextField text;
- ThreadDemo2()
- {
- getContentPane().setLayout(new FlowLayout());
- text = new JTextField(20);
- text.setEditable(false);
- text.setForeground(Color.RED);
- getContentPane().add(text);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(200, 200, 300, 300);
- setVisible(true);
- Timer t = new Timer();
- t.schedule(new TimerTask1(), 0,1000);
- }
- public static void main(String[]args)
- {
- new ThreadDemo2();
- }
- class TimerTask1 extends TimerTask
- {
- private String year;
- private String month;
- private String day;
- private String hour;
- private String min;
- private String sec;
- @Override
- public void run() {
- // TODO Auto-generated method stub
- Calendar c = Calendar.getInstance();
- year = ""+c.get(Calendar.YEAR);
- month = ""+(c.get(Calendar.MONTH)+1);
- if(month.length()<=1)
- {
- month = "0"+month;
- }
- day = ""+c.get(Calendar.DATE);
- if(day.length()<=1)
- {
- day = "0"+day;
- }
- hour = ""+c.get(Calendar.HOUR);
- if(hour.length()<=1)
- {
- hour = "0"+hour;
- }
- min = ""+c.get(Calendar.MINUTE);
- if(min.length()<=1)
- {
- min = "0"+min;
- }
- sec=""+c.get(Calendar.SECOND);
- if(sec.length()<=1)
- {
- sec = "0"+sec;
- }
- day = year + "-"+month+"-"+""+day+""+hour+":"+min+":"+sec;
- text.setText(day);
- }
- }
- }
复制代码相关类:java.util.Timer
Timer类并不是线程类,但在其内部实现中,利用线程来执行定时任务
java.util.TimerTask
TimerTask类,是一个抽像类,它实现了Runnable.
实现步骤:
一、声明一个Timer(定时器)对像。
二、书写一个TimerTask(定时器任务)类。并声明它的对像。
三、将TimerTask的变量当成Timer变量的参数设置定时任务。
作者: 许庭洲 时间: 2013-4-28 06:14
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |