有的时候你可能想写一个程序,每隔一段时间执行相关的任务,这个时候你可以使用Timer和TimerTask,非常方便。你可以参考这里。
在Java中实现一个线程有两种方法,第一是实现Runnable接口实现它的run()方法,第二种是继承Thread类,覆盖它的run()方法。下面是代码示例:
| public class DoSomething implements Runnable { public void run(){ // here is where you do something } } public class DoAnotherThing extends Thread { public void run(){ // here is where you do something } } |
Java中的线程有四种状态分别是:运行、就绪、挂起、结束。如果一个线程结束了也就说明他是一个死线程了。当你调用一个线程实例的start ()的方法的时候,这个时候线程进入就绪状态,注意并不是运行状态,当虚拟机开始分配给他CPU的运行时间片的时候线程开始进入运行状态,当线程进入等待 状态,例如等待某个事件发生的时候,这时候线程处于挂起状态。
启动一个线程你只需要调用start()方法,针对两种实现线程的方法也有两种启动线程的方法,分别如下:
| DoSomething doIt = new DoSomething(); Thread myThread = new Thread( doIt ); myThread.start(); DoAnotherThing doIt = new DoAnotherThing(); |
| public class MyThread implements Runnable { private boolean quit = false; public void run(){ public void quit(){ |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/374079/viewspace-132160/ ,如需转载,请注明出处,否则将追究法律责任。