Java计时器Timer 使用

所有类型的 Java 应用程序一般都需要计划重复执行的任务

Timer类是用来执行任务的类,它接受一个TimerTask做参数

java.util.Timer 和 java.util.TimerTask ,它们使程序员可以很容易地计划简单的任务

Timer

Timer最常用的是schedule执行任务的模式,,它可以以两种方式执行任务:

1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率.

看个简单的例子:

Java代码 复制代码
  1. importjava.io.IOException;
  2. importjava.util.Timer;
  3. publicclassTimerTest{
  4. publicstaticvoidmain(String[]args){
  5. Timertimer=newTimer();
  6. timer.schedule(newJob(),5000,10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
  7. /*
  8. //这个是用来停止此任务的,否则就一直循环执行此任务了
  9. while(1==1){
  10. try{
  11. if(2==2){
  12. timer.cancel();//使用这个方法退出任务
  13. }
  14. }catch(IOExceptione)
  15. e.printStackTrace();
  16. }*/
  17. }
  18. staticclassJobextendsjava.util.TimerTask{
  19. @Override
  20. publicvoidrun(){
  21. //TODOAuto-generatedmethodstub
  22. System.out.println("so...easy!");
  23. }
  24. }
  25. }
  26. importjava.io.IOException;
  27. importjava.util.Timer;
  28. publicclassTimerTest{
  29. publicstaticvoidmain(String[]args){
  30. Timertimer=newTimer();
  31. timer.schedule(newJob(),5000,10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
  32. /*
  33. //这个是用来停止此任务的,否则就一直循环执行此任务了
  34. while(1==1){
  35. try{
  36. if(2==2){
  37. timer.cancel();//使用这个方法退出任务
  38. }
  39. }catch(IOExceptione)
  40. e.printStackTrace();
  41. }*/
  42. }
  43. staticclassJobextendsjava.util.TimerTask{
  44. @Override
  45. publicvoidrun(){
  46. //TODOAuto-generatedmethodstub
  47. System.out.println("so...easy!");
  48. }
  49. }
  50. }
import java.io.IOException;

    import java.util.Timer;

    public class TimerTest {

    public static void main(String[] args){

    Timer timer = new Timer();

    timer.schedule(new Job(), 5000, 10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.

    /*

    //这个是用来停止此任务的,否则就一直循环执行此任务了

    while(1==1){

    try {

    if(2==2){

    timer.cancel();//使用这个方法退出任务

    }

    } catch (IOException e)

    e.printStackTrace();

    } */

    }

    static class Job extends java.util.TimerTask{

    @Override

    public void run() {

    // TODO Auto-generated method stub

    System.out.println("so...easy!");

    }

    }

    }

    import java.io.IOException;

    import java.util.Timer;

    public class TimerTest {

    public static void main(String[] args){

    Timer timer = new Timer();
timer.schedule(new Job(), 5000, 10000);//在5秒后执行此任务,每次间隔60秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.

    /*

    //这个是用来停止此任务的,否则就一直循环执行此任务了

    while(1==1){

    try {

    if(2==2){

    timer.cancel();//使用这个方法退出任务

    }

    } catch (IOException e)

    e.printStackTrace();

    } */

    }

    static class Job extends java.util.TimerTask{

    @Override

    public void run() {

    // TODO Auto-generated method stub

    System.out.println("so...easy!");

    }

    }

    }

 

TimerTask 刚才在代码里提到了 TimerTask 类。TimerTask类里有一个抽象方法run(),我们把任务写到run()方法里,或由run()执行其他方法.

完整的代码:

Java代码 复制代码
  1. publicclassTimerTest{
  2. publicstaticvoidmain(String[]args){
  3. intdelay=5000;//延迟5秒
  4. Timertimer=newTimer();//生成一个Timer对象
  5. NewTaskmyTask=newNewTask();//初始化我们的任务
  6. timer.schedule(yourTask,delay);//还有其他重载方法...
  7. }
  8. }
  9. classNewTaskextendsTimerTask{//继承TimerTask类
  10. publicvoidrun(){
  11. System.out.println("printing!");
  12. }
  13. }
  14. publicclassTimerTest{
  15. publicstaticvoidmain(String[]args){
  16. intdelay=5000;//延迟5秒
  17. Timertimer=newTimer();//生成一个Timer对象
  18. NewTaskmyTask=newNewTask();//初始化我们的任务
  19. timer.schedule(yourTask,delay);//还有其他重载方法...
  20. }
  21. }
  22. classNewTaskextendsTimerTask{//继承TimerTask类
  23. publicvoidrun(){
  24. System.out.println("printing!");
  25. }
  26. }
public class TimerTest{

    public static void main(String[] args){

    int delay=5000;//延迟5秒

    Timer timer=new Timer();//生成一个Timer对象

    NewTask myTask=new NewTask();//初始化我们的任务

    timer.schedule(yourTask,delay);//还有其他重载方法...

    }

    }

    class NewTask extends TimerTask{//继承TimerTask类

    public void run(){

    System.out.println("printing!");

    }

    }

    public class TimerTest{

    public static void main(String[] args){

    int delay=5000;//延迟5秒

    Timer timer=new Timer();//生成一个Timer对象

    NewTask myTask=new NewTask();//初始化我们的任务

    timer.schedule(yourTask,delay);//还有其他重载方法...

    }

    }

    class NewTask extends TimerTask{//继承TimerTask类

    public void run(){

    System.out.println("printing!");

    }

    }

 

这样这个程序就会在五秒钟后输出 printing!

Timer的功能是相当强大的,若要详细了解,可以查看帮助文档.完整案例!

现在大家看一下我写的关于实现LED滚屏显示动态信息!

web 监听:

Java代码 复制代码
  1. packagecom.ving.xzfw.led;
  2. importjava.util.Timer;//定时器类
  3. importjavax.servlet.ServletContextEvent;
  4. importjavax.servlet.ServletContextListener;
  5. importjavax.servlet.ServletContext;
  6. importorg.apache.log4j.Logger;
  7. importcom.ving.xzfw.util.GetInformation;
  8. //importcom.ving.xzfw.lwsp.GetConfigInfor;
  9. publicclassLEDListenerimplementsServletContextListener{
  10. privateTimertimer=null;
  11. privateLoggerlog=Logger.getLogger(getClass());
  12. //GetconfigInforconfig=newGetconfigInfor();
  13. GetInformationgetInfo=newGetInformation("bpelConfig.properties");
  14. IntegerrunTime=Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));
  15. StringfileRealPath="";
  16. StringtemplePath="";
  17. publicvoidcontextInitialized(ServletContextEventevent){
  18. //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
  19. ServletContextcontext=event.getServletContext();
  20. fileRealPath=context.getRealPath("")
  21. +System.getProperty("file.separator")+"LEDFile"
  22. +System.getProperty("file.separator");
  23. templePath=context.getRealPath("")
  24. +System.getProperty("file.separator")+"led"
  25. +System.getProperty("file.separator");
  26. timer=newTimer();
  27. log.info("定时器已启动");//添加日志,可在tomcat日志中查看到
  28. timer.schedule(newLEDTimerTack(fileRealPath,templePath),20000,runTime);
  29. log.info("已经添加任务");
  30. }
  31. publicvoidcontextDestroyed(ServletContextEventevent){//在这里关闭监听器,所以在这里销毁定时器。
  32. timer.cancel();
  33. log.info("定时器销毁");
  34. }
  35. }
  36. packagecom.ving.xzfw.led;
  37. importjava.util.Timer;//定时器类
  38. importjavax.servlet.ServletContextEvent;
  39. importjavax.servlet.ServletContextListener;
  40. importjavax.servlet.ServletContext;
  41. importorg.apache.log4j.Logger;
  42. importcom.ving.xzfw.util.GetInformation;
  43. //importcom.ving.xzfw.lwsp.GetConfigInfor;
  44. publicclassLEDListenerimplementsServletContextListener{
  45. privateTimertimer=null;
  46. privateLoggerlog=Logger.getLogger(getClass());
  47. //GetconfigInforconfig=newGetconfigInfor();
  48. GetInformationgetInfo=newGetInformation("bpelConfig.properties");
  49. IntegerrunTime=Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));
  50. StringfileRealPath="";
  51. StringtemplePath="";
  52. publicvoidcontextInitialized(ServletContextEventevent){
  53. //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
  54. ServletContextcontext=event.getServletContext();
  55. fileRealPath=context.getRealPath("")
  56. +System.getProperty("file.separator")+"LEDFile"
  57. +System.getProperty("file.separator");
  58. templePath=context.getRealPath("")
  59. +System.getProperty("file.separator")+"led"
  60. +System.getProperty("file.separator");
  61. timer=newTimer();
  62. log.info("定时器已启动");//添加日志,可在tomcat日志中查看到
  63. timer.schedule(newLEDTimerTack(fileRealPath,templePath),20000,runTime);
  64. log.info("已经添加任务");
  65. }
  66. publicvoidcontextDestroyed(ServletContextEventevent){//在这里关闭监听器,所以在这里销毁定时器。
  67. timer.cancel();
  68. log.info("定时器销毁");
  69. }
  70. }
package com.ving.xzfw.led;

    import java.util.Timer;//定时器类

    import javax.servlet.ServletContextEvent;

    import javax.servlet.ServletContextListener;

    import javax.servlet.ServletContext;

    import org.apache.log4j.Logger;

    import com.ving.xzfw.util.GetInformation;

    //import com.ving.xzfw.lwsp.GetConfigInfor;

    public class LEDListener implements ServletContextListener {

    private Timer timer = null;

    private Logger log = Logger.getLogger(getClass());

    //  GetconfigInfor config = new GetconfigInfor();

    GetInformation getInfo = new GetInformation("bpelConfig.properties");

    Integer runTime = Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));

    String fileRealPath = "";

    String templePath = "";

    public void contextInitialized(ServletContextEvent event) {

    // 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能

    ServletContext context = event.getServletContext();

    fileRealPath = context.getRealPath("")

    + System.getProperty("file.separator") + "LEDFile"

    + System.getProperty("file.separator");

    templePath = context.getRealPath("")

    + System.getProperty("file.separator") + "led"

    + System.getProperty("file.separator");

    timer = new Timer();

    log.info("定时器已启动");// 添加日志,可在tomcat日志中查看到

    timer.schedule(new LEDTimerTack(fileRealPath, templePath), 20000, runTime);

    log.info("已经添加任务");

    }

    public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。

    timer.cancel();

    log.info("定时器销毁");

    }

    }

    package com.ving.xzfw.led;

    import java.util.Timer;//定时器类

    import javax.servlet.ServletContextEvent;

    import javax.servlet.ServletContextListener;

    import javax.servlet.ServletContext;

    import org.apache.log4j.Logger;

    import com.ving.xzfw.util.GetInformation;

    //import com.ving.xzfw.lwsp.GetConfigInfor;

    public class LEDListener implements ServletContextListener {

    private Timer timer = null;

    private Logger log = Logger.getLogger(getClass());

    //GetconfigInfor config = new GetconfigInfor();

    GetInformation getInfo = new GetInformation("bpelConfig.properties");

    Integer runTime = Integer.parseInt(getInfo.getProperty("led.TimingRunTime"));

    String fileRealPath = "";

    String templePath = "";
public void contextInitialized(ServletContextEvent event) {

    // 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能

    ServletContext context = event.getServletContext();

    fileRealPath = context.getRealPath("")

    + System.getProperty("file.separator") + "LEDFile"

    + System.getProperty("file.separator");

    templePath = context.getRealPath("")

    + System.getProperty("file.separator") + "led"

    + System.getProperty("file.separator");

    timer = new Timer();

    log.info("定时器已启动");// 添加日志,可在tomcat日志中查看到

    timer.schedule(new LEDTimerTack(fileRealPath, templePath), 20000, runTime);

    log.info("已经添加任务");

    }

    public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。

    timer.cancel();

    log.info("定时器销毁");

    }

    }

 

Java代码 复制代码
  1. packagecom.ving.xzfw.led;
  2. importjava.util.TimerTask;
  3. publicclassLEDTimerTackextendsTimerTask{
  4. StringfileRealPath="";
  5. StringtemplePath="";
  6. Stringtype="";
  7. intfloor;
  8. publicLEDTimerTack(StringfileRealPath,StringtemplePath,Stringtype,Integerfloor){
  9. this.fileRealPath=fileRealPath;
  10. this.templePath=templePath;
  11. this.type=type;
  12. this.floor=floor;
  13. }
  14. publicLEDTimerTack(StringfileRealPath,StringtemplePath){
  15. this.fileRealPath=fileRealPath;
  16. this.templePath=templePath;
  17. }
  18. publicvoidrun(){
  19. for(inti=1;i<=3;i++)
  20. //呵呵,这里就是led动态生成信息的代码!
  21. XlsUtil.createHtmlFile(templePath,fileRealPath,i);
  22. }
  23. }
stm32H743基于CubeMX配置为双ADC多通道DMA规则采样 stm32H743的ADC支持的最大频率为36MHz,有相关资料上说是可以超频,具体技术细节不多讨论。 需求: 使用stm32H743的ADC采集5路ovrc 阅读详情

相关推荐

Anthropic API接入指南:连接失败、403鉴权与Claude Code集成排查

在AI应用开发中,API接入与鉴权机制是开发者绕不开的基础工程问题。无论是调用云端模型服务还是自建网关,网络连通性、HTTP状态码语义、模型路由映射都会直接影响服务可用性。本文从通用的网络诊断与鉴权原理出发,梳理了从TCP连接失败到403权限拒绝的典型链路,并深入解析网关模型路由匹配机制。在此基础上,进一步说明如何通过环境变量完成Claude Code与VS Code的本地集成,以及一套基于Python的可复现接入方案。内容涵盖Anthropic API高频报错定位、curl冒烟测试、SDK工程化实践,适合

weixin_28743405的博客 464

java 定时器的几种实现方式以及 配置参数的说明

2.java中常见的定时器1)借助Java.util.Timer来实现2)OpenSymphony社区提供的Quartz来实现3.介绍Timer利用Timer开发定时任务是主要分为两个步骤:1)创建定时任务类示例代码:packageorg.lzstone.actionimportjava.ut...

weixin_34209406的博客 498

Tushare Day2——了解stock_basic数据并根据行业和地区进行统计

了解stock_basic数据 1  stock_basic基础信息2  导入包和stock_basic数据、查看基本信息3  根据行业列进行统计3.1  1.先把不同行业列举出来,看一下一共有多少种行业3.2  2.统计每个行业分别有多少家公司3.3  3.把行业从array的二维数组形式变成list形式3.4  4.把行业从list形式转换成文本形式3.5&nbsp

绒绒的Routine 2796

Java定时任务调度详解

前言 在实际项目开发中,除了Web应用、SOA服务外,还有一类不可缺少的,那就是定时任务调度。定时任务的场景可以说非常广泛,比如某些视频网站,购买会员后,每天会给会员送成长值,每月会给会员送一些电影券;比如在保证最终一致性的场景中,往往利用定时任务调度进行一些比对工作;比如一些定时需要生成的报表、邮件;比如一些需要定时清理数据的任务等。本篇博客将系统的介绍定时任务调度,会涵盖Timer、Sc...

weixin_34295316的博客 604

Jev模型入门:从API接入到本地部署的完整实践指南

大模型的应用方式正从单一聊天窗口转向复杂的自动化工作流,而推理模型因具备指令跟随与结构化输出能力,成为构建Agent和数据处理管线的关键组件。Jev作为面向通用场景的推理模型,不仅提供了OpenAI兼容的API接口,还支持本地量化部署,兼顾隐私、可控性与长期成本。本文从模型定位出发,明确Jev与基座模型的差异,随后介绍密钥管理、API调用、参数调优,并深入演示基于Ollama与llama.cpp的本地部署流程,包括GGUF模型文件与chat template的匹配要点。针对实践中的常见问题,如密钥泄露、ma

weixin_29057237的博客 355

瑞芯微rk3568移植openbmc(一)----关于ob移植的优缺点

基于rock3a的单板,CPU为瑞芯微rk3568的环境,移植了openbmc

feixiang3839的专栏 5535

Java Swing Timer:计时器组件

1 Java Swing Timer:计时器组件 计时器(Timer)组件可以在指定时间间隔触发一个或多个 ActionEvent。设置计时器的过程包括创建一个 Timer 对象,在该对象上注册一个或多个动作侦听器,以及使用 start() 方法启动该计时器。 例如,以下代码创建并启动一个每秒(该时间由 Timer 构造方法的第一个参数指定)触发一次动作事件的计时器。Timer 构造方法的第二个...

书香水墨 5120

《Ventoy 制作系统安装 U 盘的具体步骤》

然后您可以在电脑的磁盘管理中对 U 盘进行快速格式化,选择 FAT32 或 NTFS 文件系统。至此,Ventoy 系统安装 U 盘就制作完成了。您可以在需要安装系统的电脑上,从 U 盘启动,然后选择相应的系统镜像进行安装。安装完成后,将您需要的操作系统镜像文件(如 Windows、Linux 等的 ISO 格式镜像)复制到 U 盘的根目录。在安装程序中,选择您插入的 U 盘设备,确保选择正确,以免误操作。2. 确认选择的 U 盘盘符正确,防止误操作导致其他磁盘数据丢失。点击“安装”按钮,等待安装完成。

jiyiwangluokeji的博客 2664

Java Swing的计时器组件Timer

概述 Timer组件是计时器,可以在指定时间间隔触发一个或多个ActionEvent。 可以达成的效果如例: 快速入门 第一步,创建Timer。 第二步,向Timer构造器中传入两个参数,分别是延迟和事件。 第三步,调用start()方法启用计时器。 public static void main(String[] args) { JFrame frame = new JFrame(); frame.setTitle("Timer测试");

二木成林 3273

提升RAG效果:为何 JSON 格式远胜 Markdown?

在构建强大的 RAG (检索增强生成) 系统时,文档解析是至关重要的第一步。它直接影响着后续的检索效率和生成质量。在众多文档格式中,JSON (JavaScript Object Notation) 格式正逐渐展现出其相对于传统 Markdown 格式的巨大优势。本文将深入探讨 JSON 在 RAG 系统文档解析中的卓越之处,并结合具体案例,让你理解为何 JSON 才是构建下一代智能应用的更优选择。RAG 系统的核心目标是让模型能够利用外部知识库,生成更精准、更贴合实际的答案。

simoncool23的博客 2714

博途V17 & PLCSIM & FactoryIO 连接教程

PLCSIM V17 和 FactoryIO 连接教程前言一、软件版本二、连接步骤1. 连接PLCSIM2. 博途编程3.连接FactoryIO总结 前言 该文详细讲解了新手入门博途,并通过使用自带PLCSIM和FactoryIO实现连接。 一、软件版本 TIA Portal V17 S7-PLCSIM V17 Factory IO V2.5.1 二、连接步骤 1. 连接PLCSIM 打开PLCSIM 进入项目模式 新建仿真项目 2. 博途编程 将F

soledad_chao的博客 2万+

java的计时器函数_Java计时器Timer和TimerTask用法总结(源码)

在家学技术实在是不好坚持,心里老是想给自己放个假,但是现在俺又太菜,又想赶赶技术。前天做一个五子棋程序,遇到了计时器功能的需求,但是这个我没用过,就总结一下吧,不过虽然是会用了,但是和swing的代码整合还是有问题,困扰好久,到现在也没解决,一气之下,看了三部电影,呵呵。这个计时器,就是为了使在下五子棋过程中,黑白双方,轮流下的时候,给下棋一方计时,并且要求,时间动态显示在面板上,就是一秒一秒在走...

weixin_32058239的博客 397

从仿真到流片:手把手教你优化65nm CMOS电荷泵的电流匹配与稳定性

本文详细介绍了在65nm CMOS工艺下优化电荷泵电流匹配与稳定性的工程实践指南。通过蒙特卡洛仿真、运放反馈结构版图技巧和全差分结构设计,实现优于1%的电流匹配精度和±2%以内的电流稳定性,特别针对current mismatch问题提供了有效的解决方案。

weixin_42522320的博客 415

java 计时器线程 Timer类

java提供了一个很方便的timer类,该类在javax.swing包中。当某些操作需要周期性执行 就可以使用计时器。 我们可以使用Timer类的构造方法Timer(int a,Object b)创建一个计时器,其中参数a的单位是毫秒,确定计时器每隔a 毫秒振铃一次,参数b是计时器的 package Example12_12; import javax.swing.*; import ja

苏苏爱自由 9659

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Java计时器Timer 使用1 (转)

a651944226的专栏 1210

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

android java 计时器Timer

Timer的执行是基于TimerTask的,而TimerTask在执行时会占用一个线程,如果我们同时执行大量的任务,可能会导致线程池被用尽,从而影响系统的性能和稳定性。Timer再执行任务时是在新线程中进行的,因此多个定时器任务可能会并发的执行,这可能会导致线程安全问题,为了避免这种情况的发生,我们可以使用HandlerThread或者单独的线程来执行定时器任务。Timer是Android中的一个非常有用的计时器类,他可以用于定期执行任务,在使用Timer时,需要注意线程安全问题,异常处理和性能问题。

awildpig110的博客 564

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

java timer计时_多种计时器的比较与分析

多种计时器的比较与分析王 越2008 年 5 月 26 日发布介绍计时器可以提供运行基于时间的工作任务的功能,在计时器的管理下,特定的任务可在某一时间运行一次,也可以按指定的时间间隔反复运行。在众多厂商提供的计时器中应用得比较多的有以下三种:java.util.TimerSun JDK 提供的一种轻量级的计时器。Commonj TimerIBM 和 BEA 联合制定和推出的一种适用于 J2EE 环...

weixin_39637049的博客 193

【Java多线程】计时器Timer/ScheduledExecutorService的使用

Timer 是 Java 提供的一个简单的任务调度工具(位于 java.util 包),用于在指定的时间执行任务(一次性或周期性执行)。:所有任务都在同一个线程中执行,如果一个任务执行时间过长,会影响其他任务的调度。:如果某个任务抛出未捕获的异常,整个 Timer 会终止,后续任务不会执行。如果任务执行时间超过 period,下一次任务会 立即开始(可能并发执行)。:如果系统时间被调整(如手动修改时间),可能导致任务执行不准确。:只需要在某个时间点执行一次的任务(如延迟初始化、超时任务)。

to_mountain的博客 1097

java timer 计时器_Java的Timer定时器

Timer主要用于Java线程里指定时间或周期运行任务,它是线程安全的,但不提供实时性(real-time)保证。上面提到了守护线程的概念。Java分为两种线程:用户线程和守护线程。所谓守护线程,是指在程序运行的时候在后台提供一种通用服务的线程,比如垃圾回收线程就是一个很称职的守护者,并且这种线程并不属于程序中不可或缺的部分。因 此,当所有的非守护线程结束时,程序也就终止了,同时会杀死进程中的所有...

weixin_29867607的博客 308

JAVA Timer()实现可重置计时器

要去实现一个计时器功能:倒记时10秒,倒计时结束后,触发事件A,倒计时过程中,若触发事件B,则重置计时器,重新倒计时十秒。

weixin_42152152的博客 2391

Java计时器Timer 使用 完整案例(转)

a651944226的专栏 1815

java 计时器标记位_Java计时器Timer和TimerTask用法总结(源码)

在家学技术实在是不好坚持,心里老是想给自己放个假,但是现在俺又太菜,又想赶赶技术。前天做一个五子棋程序,遇到了计时器功能的需求,但是这个我没用过,就总结一下吧,不过虽然是会用了,但是和swing的代码整合还是有问题,困扰好久,到现在也没解决,一气之下,看了三部电影,呵呵。这个计时器,就是为了使在下五子棋过程中,黑白双方,轮流下的时候,给下棋一方计时,并且要求,时间动态显示在面板上,就是一秒一秒在走...

weixin_34405261的博客 259

Java计时器Timer的使用

Java计时器Timer的使用

hfdgjhv的博客 6252

java计时器_Java Swing Timer:计时器组件

计时器(Timer)组件可以在指定时间间隔触发一个或多个 ActionEvent。设置计时器的过程包括创建一个 Timer 对象,在该对象上注册一个或多个动作侦听器,以及使用 start() 方法启动该计时器。例如,以下代码创建并启动一个每秒(该时间由 Timer 构造方法的第一个参数指定)触发一次动作事件的计时器。Timer 构造方法的第二个参数指定接收计时器动作事件的监听器。int delay...

weixin_39617669的博客 410

java multiple timer_java - 在Android中使用单个计时器与多个计时器来调度TimerTask - 堆栈内存溢出...

我想我不完全了解Timer和TimerTask在Java和Android中的工作方式。 现在,我定义了许多定期任务,这些任务要在计时器中安排。我想知道我应该使用单个计时器来安排任务,还是为每个任务使用不同的计时器实例? 计时器有自己的线程吗? 预定任务是否在新线程中执行? 后台发生了什么?这些方法之间有什么区别?方法1的样例代码:private void initTasks() {Time...

weixin_39621044的博客 210

17、Java Swing Timer:计时器组件

计时器(Timer)组件可以在指定时间间隔触发一个或多个 ActionEvent。 设置计时器的过程包括创建一个 Timer 对象,在该对象上注册一个或多个动作侦听器,以及使用 start() 方法启动该计时器。 例如,以下代码创建并启动一个每秒(该时间由 Timer 构造方法的第一个参数指定)触发一次动作事件的计时器。Timer 构造方法的第二个参数指定接收计时器动作事件的监听器。 int delay=1000; //时间间隔,单位为毫秒 ActionListener taskPerformer=n

you can you up up up的博客 913
上一篇: Java计时器Timer 使用
下一篇: 工厂模式
MyJavaBlog
博客等级 码龄16年 11粉丝 126原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值