您的位置:

java计时器,java计时器倒计时

本文目录一览:

用JAVA编写计时器

计时器可以使用timer类也可以使用线程类来操作,下面是Thread做的简单的计时器

public class Calculagraph extends Thread {

public static void main(String[] args) {

new Calculagraph().start();

}

private long now = 0l;

private long start = System.currentTimeMillis();// 程序启动时间的毫秒值

private long time;

public void run() {

while (true) {

now = System.currentTimeMillis();// 获取一秒之后的毫秒值

time = now - start;// 两个时间相减的到毫秒差

System.out.format("%02d:%02d:%02d\n",

time / (1000 * 60 * 60) % 60/* 时 */, 

time / (1000 * 60)% 60/* 分 */, 

time / 1000 % 60/* 秒 */);// 格式化字符串输出

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

JAVA计时器,怎么写

import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class TimeCount extends JFrame implements ActionListener{

ThreadCount tc=new ThreadCount(this);

Thread thread=new Thread(tc);

JPanel panelN=new JPanel(),panelC=new JPanel();

JLabel label=new JLabel("计时器");

JButton butnStart=new JButton("开始");

boolean toEnd;

public TimeCount() {

setBounds(100,100,300,300);

setVisible(true);

label.setFont(new Font(null,Font.BOLD,22));

panelN.add(label);

add(panelN,BorderLayout.NORTH);

panelC.add(butnStart);

add(panelC,BorderLayout.CENTER);

butnStart.addActionListener(this);

validate();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent arg0) {

if(arg0.getSource()==butnStart){

if(!thread.isAlive()){

thread=new Thread(tc);

thread.start();

}else {

toEnd=true;

}

}

}

public static void main(String[] args) {

new TimeCount();

}

}

class ThreadCount implements Runnable{

TimeCount lc;

public ThreadCount(TimeCount lc) {

super();

this.lc = lc;

}

public void run() {

int i=1;

while(true){

if(lc.toEnd){

lc.toEnd=false;

lc.butnStart.setText("开始");

return;

}

try {

Thread.sleep(2);

} catch (InterruptedException e) {

// TODO: handle exception

}

i+=2;

int min=i/60000;

int second=(i%60000)/1000;

int mm=i%1000;

String show="";

if(min0)

show+=min+":";

if(second0)

show+=second+".";

show+=mm;

lc.label.setText(show);

}

}

}

满意请采纳。

如何用java实现一个计时器?

用java实现一个计时器的方法:

public class TestDingShi implements Runnable

{

Thread xc;

Dao dao=new DaoImpl();

public TestDingShi()

{

xc=new Thread(this);//线程开启

xc.start();

}

public void run()

{

while (true)

{

try

{

xc.sleep(1000);//睡眠开始计时

}

catch (InterruptedException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

//TODO定时在此

}

}

}