public class Daojishi extends Thread{
public static void main(String[] args) throws Exception{
for(int i=10;i>0;i--){
Thread.sleep(1000);
System.out.println("倒計時:"+i);
}
}
}
❷ 如何用java實現一個計時器
怎麼還沒人回答,看不過去了,用不用多線程根據你的程序需要,
import java.io.IOException;
import java.util.Timer;
public class TimerTest {
public static void main(String[] args){
Timer timer = new Timer();
timer.schele(new MyTask(), 1000, 2000);//在1秒後執行此任務,每次間隔秒,如果傳遞一個Data參數,就可以在某個固定的時間執行這個任務.
while(true){//這個是用來停止此任務的,否則就一直循環執行此任務了
try {
int ch = System.in.read();
if(ch-'c'==0){
timer.cancel();//使用這個方法退出任務
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class MyTask extends java.util.TimerTask{
@Override
public void run() {
//你要進行的操作
}
}
}
大概就是這樣了,在根據你的業務需要查一下資料,就可以搞定了!
❸ JAVA 計時器 求大神
//聲明圖形界面元素
privateJLabellab_time;
privateJButtonbut_start;
privateJButtonbut_end;
privateJButtonbut_reset;
//初始化界面元素,布局,注冊時間監聽器
setLayout(null);
setSize(400,300);
lab_time=newJLabel("");
lab_time.setBounds(0,10,100,50);
but_start=newJButton("開始");
but_start.setBounds(100,10,100,50);
but_end=newJButton("停止");
but_end.setBounds(200,10,100,50);
but_reset=newJButton("重置");
but_reset.setBounds(300,10,100,50);
myThread=newThread();
setTitle("計時器");
add(lab_time);
add(but_start);
add(but_end);
add(but_reset);
but_start.addActionListener(this);
but_end.addActionListener(this);
but_reset.addActionListener(this);
//事件處理方法
if(event.getSource()==but_start)
{
myThread.start();
}
if(event.getSource()==but_end)
{
myThread.stop();
}
if(event.getSource()==but_reset)
{
hour=0;
min=0;
sec=0;
this.showTime();
}
//線程處理代碼
while(true)
{
try{
Thread.sleep(1000);
sec++;
if(sec==60)
{
min++;
sec=0;
}
if(min==60)
{
hour++;
min=0;
}
this.showTime();
}catch(Exceptione){
e.printStackTrace();
}
}
//設置窗體上顯示時間
lab_time.setText(strTime);
好不容易打出來的,不知道你考試結束了嘛、希望能採納吧!
❹ 用java編寫一個計數器或計時器
import java.io.IOException;
import java.util.Timer;
public class TimerTest {
public static void main(String[] args){
Timer timer = new Timer();
timer.schele(new MyTask(), 1000, 2000);//在1秒後執行此任務,每次間隔2秒,如果傳遞一個Data參數,就可以在某個固定的時間執行這個任務.
while(true){//這個是用來停止此任務的,否則就一直循環執行此任務了
try {
int ch = System.in.read();
if(ch-'c'==0){
timer.cancel();//使用這個方法退出任務
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class MyTask extends java.util.TimerTask{
@Override
public void run() {
//你要進行的操作
}
}
}