1. 程式人生 > >Thread sleep()休眠

Thread sleep()休眠

ktr cep int new t static 中斷線程 print sets ring

Thread sleep()休眠就是讓線程進入休眠狀態TIMED_WAITING,sleep("毫秒數"),當休眠時間到了之後繼續線程。當然也可以用中斷線程interrupt()來中斷線程休眠。判斷線程是否休眠if(ts.getstate()==state.TIMED_WAITING)

利用線程休眠來做秒表

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Time extends JFrame{
public Time(){
setTitle("秒表");

setSize(300,300);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel label=new JLabel("00:000");
Font f=new Font("微軟雅黑",Font.BOLD,56);
label.setFont(f);
label.setBounds(30,10,250,100);
add(label);
JButton bt=new JButton("開始");
bt.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
long s=0,ms,start=System.currentTimeMillis();//獲取系統當前時間
while (true){
ms=System.currentTimeMillis()-start;
s=ms/1000;ms=ms%1000;
String ss=s+"",sms=ms+"";
if (s<10) ss="0"+ss;
if (ms<10) sms="00"+ms;
else if (ms<100) sms="0"+ms;
String str=ss+":"+sms;
label.setText(str);
// System.out.println(str);
try {
Thread.sleep(10);//休眠10毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
bt.setBounds(30,200,80,30);
add(bt);
JButton bt1=new JButton("暫停");
bt1.setBounds(150,200,80,30);
add(bt1);
JLabel b=new JLabel();
add(b);

}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Time();
}
});
}
}

Thread sleep()休眠