首页 技术 正文
技术 2022年11月23日
0 收藏 832 点赞 3,689 浏览 1534 个字

Thread sleep()休眠就是让线程进入休眠状态TIMED_WAITING,sleep(“毫秒数”),当休眠时间到了之后继续线程。当然也可以用中断线程interrupt()来中断线程休眠。判断线程是否休眠if(ts.getstate()==state.TIMED_WAITING)

线程的6中状态(1).NEW新建状态(2).Runnable运行状态(3).TIMED_WAITING休眠状态(4).WAITING等待(5).BLOCKED阻塞(6).TERMINATED退出

Wait() 与sleep()方法的异同
同:
都使线程进入休眠状态。
都会被interrupt打断。
wait(long)\sleep(long)都会因超时而醒来。
异:
wait,将释放监视器锁。sleep,不释放锁。
wait时,必须执有监视器锁。sleep时,与锁无关。
wait与notify配套使用。sleep不可以。

利用线程休眠来做秒表

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();
}
});
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,903
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,428
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,245
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,057
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,688
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,726