线程小结

来源:互联网 发布:linux怎么修改用户组 编辑:程序博客网 时间:2024/05/17 07:10

这两天我们开始学习线程,就学到的知识做一下总结:

1、 线程的实现有四种方法:

l        继承extends

l        实现Runnable接口

l        通过内部类的形式

l        通过继承TimerTask


对于这几个方法,都是先继承线程或者实现Runnable接口或者继承TimerTask,然后实现Run函数,再启动线程。

对于继承TimerTask,说明性代码如下:

publicclass TimerPrintextendsTimerTask{

       privateintrunCount=0;

       publicstaticvoid main(String args[]){

              //创建一个定时器对象

              Timer timer=new Timer();

              //创建一个定时任务对象

              TimerPrint dw=new TimerPrint();

              //调用这个定时任务在程序启动5秒后,每隔3秒运行一次

              timer.schedule(dw, 5000, 3000);

       }

       //重写继承TimerTask中的run方法,作为线程运行时被调用

       publicvoid run(){

              runCount++;

              System.out.println(runCount+"次定时运行:"+System.currentTimeMillis()/1000);

       }

      

}

 线程能让很多东西跑起来,是很有用很“好玩”的。

原创粉丝点击